diff --git a/cpp/2302/230221.cpp b/cpp/2302/230221.cpp new file mode 100644 index 0000000..9811165 --- /dev/null +++ b/cpp/2302/230221.cpp @@ -0,0 +1,28 @@ +#include +#include + +/** + * 540. Single Element in a Sorted Array + * + * You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. + * Return the single element that appears only once. + * Your solution must run in O(log n) time and O(1) space. + */ + +class Solution { +public: + static int singleNonDuplicate(const std::vector& nums) { + int L = 0, R = nums.size() >> 1; // inclusive + while (L < R) { + int M = (L + R) >> 1; + if (nums[(M << 1) | 1] - nums[M << 1]) R = M; + else L = M + 1; + } + return nums[L << 1]; + } +}; + +int main() { + std::cout << Solution::singleNonDuplicate({3,3,7,7,10,11,11}); + return 0; +} diff --git a/cpp/2302/CMakeLists.txt b/cpp/2302/CMakeLists.txt index 8a12700..68331da 100644 --- a/cpp/2302/CMakeLists.txt +++ b/cpp/2302/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2302) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2302 230221-CN.cpp) +ADD_EXECUTABLE(2302 230221.cpp)