-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathSingle Element in a Sorted Array.cpp
52 lines (37 loc) · 1.2 KB
/
Single Element in a Sorted Array.cpp
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
46
47
48
49
50
51
52
/*
Solution by Rahul Surana
***********************************************************
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.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int s = 0,e = nums.size()-1;
while(s<=e){
int m = s+ (e - s) / 2;
cout << m <<" "<<nums[m]<< "\n";
if(m>0 && nums[m] == nums[m-1]){
if(m%2 == 0) e = m-2;
else{
s = m+1;
}
}
else if(m<nums.size()-1 && nums[m] == nums[m+1]){
if(m%2==0){
s = m+2;
}
else{
e = m-1;
}
}
else{
return nums[m];
}
}
return nums[s];
}
};