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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public: int singleNonDuplicate(vector<int>& nums) { if(nums.size() == 1) return nums[0]; int l = 0, r = nums.size() - 1; while(l <= r) { int m = (l + r) / 2; if(m & 1) { if(nums[m-1] == nums[m]) l = m + 1; else { if(m + 1 == nums.size() or nums[m+1] != nums[m]) return nums[m]; r = m - 1; } } else { if(nums[m+1] == nums[m]) l = m + 1; else { if(m - 1 < 0 or nums[m-1] != nums[m]) return nums[m]; r = m - 1; } } } return -1; } };
|