forked from yesiamrajeev/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleElementInSortedArray.java
More file actions
33 lines (28 loc) · 980 Bytes
/
SingleElementInSortedArray.java
File metadata and controls
33 lines (28 loc) · 980 Bytes
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
public class SingleElementInSortedArray {
public int singleNonDuplicate(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
// Ensure mid is even
if (mid % 2 == 1) {
mid--;
}
// Check pair
if (nums[mid] == nums[mid + 1]) {
// Single element lies on the right side
left = mid + 2;
} else {
// Single element lies on the left side
right = mid;
}
}
// Left will point to the single element
return nums[left];
}
// Main method for testing
public static void main(String[] args) {
SingleElementInSortedArray solution = new SingleElementInSortedArray();
int[] nums = {1,1,2,3,3,4,4,8,8};
System.out.println(solution.singleNonDuplicate(nums)); // Output: 2
}
}