540. Single Element in a Sorted Array

540. Single Element in a Sorted Array

Description

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.

Example 1:

1
2
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2:

1
2
Input: nums = [3,3,7,7,10,11,11]
Output: 10

Constraints:

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^5

Hints/Notes

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size();
int low = 0, high = n - 1;
while (low < high) {
int mid = (high + low) / 2;
bool halvesAreEven = (high - mid) % 2 == 0;
if (nums[mid + 1] == nums[mid]) {
if (halvesAreEven) {
low = mid + 2;
} else {
high = mid - 1;
}
} else if (nums[mid - 1] == nums[mid]) {
if (halvesAreEven) {
high = mid - 2;
} else {
low = mid + 1;
}
} else {
return nums[mid];
}
}
return nums[low];
}
};