forked from USPCodeLabSanca/dev.hire-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path540.cpp
More file actions
41 lines (34 loc) · 1.02 KB
/
Copy path540.cpp
File metadata and controls
41 lines (34 loc) · 1.02 KB
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
34
35
36
37
38
39
40
41
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int start = 0;
int end = nums.size() - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
int adjacent = adjacentfOf(nums, mid);
if (adjacent == -1) {
return nums[mid];
} else if (adjacent == 0) {
if (mid % 2 == 0) {
end = mid - 1;
} else {
start = mid + 1;
}
} else {
if (mid % 2 == 0) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return 0;
}
int adjacentfOf(vector<int>& nums, int i) {
if ((i - 1) >= 0 && nums[(i - 1)] == nums[i])
return 0;
if ((i + 1) < nums.size() && nums[(i + 1)] == nums[i])
return 1;
return -1;
}
};