-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleelemnt.java
More file actions
45 lines (42 loc) · 1.35 KB
/
singleelemnt.java
File metadata and controls
45 lines (42 loc) · 1.35 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
import java.util.*;
public class singleelemnt {
public static int singleNonDuplicate(int[] nums) {
int n = nums.length; // Size of the array.
// Edge cases:
if (n == 1)
{
return nums[0];
}
if (nums[0]!=nums[1])
{
return nums[0];
}
if (nums[n-1]!=nums[n-2])
return nums[n-1];
int low = 1, high = n - 2;
while (low <= high) {
int mid = (low + high) / 2;
// If arr[mid] is the single element:
if (nums[mid]!=nums[mid-1] && nums[mid] != nums[mid+1])
{
return nums[mid];
}
if ((mid % 2 == 1 && nums[mid] == nums[mid - 1])
|| (mid % 2 == 0 && nums[mid] == nums[mid + 1])) {
//eliminate the left half:
low = mid + 1;
}
//we are in the right:
else {
//eliminate the right half:
high = mid - 1;
}
}
return -1;
}
public static void main(String[] args)
{
int[] arr = {1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6};
System.out.println(singleNonDuplicate(arr));
}
}