-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleElement.cpp
More file actions
33 lines (31 loc) · 851 Bytes
/
Copy pathSingleElement.cpp
File metadata and controls
33 lines (31 loc) · 851 Bytes
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
28
29
30
31
32
33
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size();
if (n== 1){
return nums[0];
}
if (nums[0] != nums[1]) {
return nums[0];
}
if (nums[n-1] != nums[n-2]){
return nums[n-1];
}
int low = 1; int high = n-2;
while (low<=high) {
int mid = low +(high-low)/2;
if (nums[mid] != nums[mid+1] && nums[mid] != nums[mid-1]) {
return nums[mid];
}
// left portion;
if ((mid%2==1 && nums[mid]==nums[mid-1]) ||
(mid%2==0 && nums[mid]==nums[mid+1] )) {
low = mid+1;
// right portion;
}else {
high = mid-1;
}
}
return -1;
}
};