[LeetCode] Single Element in a Sorted Array

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) { //odd
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;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/single-element-in-a-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.