Skip to content

Commit 94b5a78

Browse files
authored
Update Single Element in a Sorted Array.java
1 parent c31377e commit 94b5a78

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed
Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,25 @@
11
class Solution {
2-
public int singleNonDuplicate(int[] nums) {
3-
boolean evenInd = true;
4-
for (int i=0;i<nums.length-1;i++) {
5-
if (nums[i] != nums[i+1] && evenInd) {
6-
return nums[i];
7-
}
8-
evenInd = evenInd ? false : true;
9-
}
10-
11-
return nums[nums.length-1];
2+
public int singleNonDuplicate(int[] nums) {
3+
if (nums.length == 1) {
4+
return nums[0];
125
}
6+
return binarySearchHelper(nums, 0, nums.length - 1);
7+
}
8+
9+
private int binarySearchHelper(int[] nums, int start, int end) {
10+
if (start > end) {
11+
return Integer.MIN_VALUE;
12+
}
13+
int mid = (start + end) / 2;
14+
if (mid == 0 && mid + 1 < nums.length && nums[mid] != nums[mid + 1]) {
15+
return nums[mid];
16+
}
17+
if (mid == nums.length - 1 && mid - 1 >= 0 && nums[mid] != nums[mid - 1]) {
18+
return nums[mid];
19+
}
20+
if (mid + 1 < nums.length && nums[mid] != nums[mid + 1] && mid - 1 >= 0 && nums[mid] != nums[mid - 1]) {
21+
return nums[mid];
22+
}
23+
return Math.max(binarySearchHelper(nums, start, mid - 1), binarySearchHelper(nums, mid + 1, end));
24+
}
1325
}

0 commit comments

Comments
 (0)