-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingle_Element_Sorted_inArray.java
More file actions
41 lines (34 loc) · 1.07 KB
/
Single_Element_Sorted_inArray.java
File metadata and controls
41 lines (34 loc) · 1.07 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(int[] nums) {
if (nums.length == 1) {
return nums[0];
} else if (nums[0] != nums[1]) {
return nums[0];
} else if (nums[nums.length - 1] != nums[nums.length - 2]) {
return nums[nums.length - 1];
}
int start = 1;
int end = nums.length - 2;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] != nums[mid - 1] && nums[mid] != nums[mid + 1]) {
return nums[mid];
}
if (mid % 2 == 0) {
if (nums[mid] == nums[mid + 1]) {
start = mid + 2;
} else {
end = mid - 1;
}
}
else {
if (nums[mid] == nums[mid - 1]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return -1;
}
}