From d6902d7c66fa896cb6ace542a150900af4e92e9d Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Mon, 14 Feb 2022 09:03:24 +0800 Subject: [PATCH] add: 220214-CN --- 2202/220214-CN.cpp | 35 +++++++++++++++++++++++++++++++++++ 2202/CMakeLists.txt | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 2202/220214-CN.cpp diff --git a/2202/220214-CN.cpp b/2202/220214-CN.cpp new file mode 100644 index 0000000..b1bedd0 --- /dev/null +++ b/2202/220214-CN.cpp @@ -0,0 +1,35 @@ +#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(); + if (R == 1) + return nums[0]; + + // Interval [L, R) + while (R - L > 1) { + int M = (L + R) >> 1; + if (nums[M] == nums[M ^ 1]) { + L = 1 + (M | 1); + } else { + R = (M & (~1)) + 1; + } + } + + return nums[L]; + } +}; + +int main() { + std::printf("%d\n", Solution::singleNonDuplicate({1,1,2,3,3})); + return 0; +} diff --git a/2202/CMakeLists.txt b/2202/CMakeLists.txt index beda610..faaa539 100644 --- a/2202/CMakeLists.txt +++ b/2202/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2202) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2202 220213.cpp) +ADD_EXECUTABLE(2202 220214-CN.cpp)