-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode540.cpp
More file actions
72 lines (56 loc) · 1.57 KB
/
leetcode540.cpp
File metadata and controls
72 lines (56 loc) · 1.57 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// 540. Single Element in a Sorted Array
// Solved
// Medium
// Topics
// Companies
// 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.
// Example 1:
// Input: nums = [1,1,2,3,3,4,4,8,8]
// Output: 2
// Example 2:
// Input: nums = [3,3,7,7,10,11,11]
// Output: 10
// Constraints:
// 1 <= nums.length <= 105
// 0 <= nums[i] <= 105
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;
if(mid>0 && mid<nums.size()-1){
if(mid%2==0){
if(nums[mid]!=nums[mid-1] && nums[mid]!=nums[mid+1]){
return nums[mid];
}
else if(nums[mid]==nums[mid-1]){
end=mid-1;
}
else{
start=mid+1;
}
}
else{
if(nums[mid]!=nums[mid-1] && nums[mid]!=nums[mid+1]){
return nums[mid];
}
else if(nums[mid]==nums[mid-1]){
start=mid+1;
}
else{
end=mid-1;
}
}
}
else
{
break;
}
}
return nums[start];
}
};