-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay-10-single-element-in-a-sorted-array.cpp
More file actions
45 lines (44 loc) · 1.11 KB
/
Copy pathDay-10-single-element-in-a-sorted-array.cpp
File metadata and controls
45 lines (44 loc) · 1.11 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
42
43
44
45
class Solution
{
public:
int singleNonDuplicate(vector<int> &nums)
{
int n = nums.size();
int low = 0, high = n - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
// since all other elements are present twice, we check one position left
// and one position right of mid element to find out the answer
if (mid < n - 1 && nums[mid] == nums[mid + 1])
{
int cnt = mid + 2;
if (cnt & 1)
{
high = mid - 1;
}
else
{
low = mid + 2;
}
}
else if (mid > 0 && nums[mid - 1] == nums[mid])
{
int cnt = mid + 1;
if (cnt & 1)
{
high = mid - 2;
}
else
{
low = mid + 1;
}
}
else
{
return nums[mid];
}
}
return -1;
}
};