-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSSingleElement.java
More file actions
39 lines (39 loc) · 1017 Bytes
/
BSSingleElement.java
File metadata and controls
39 lines (39 loc) · 1017 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
34
35
36
37
38
39
import java.util.*;
public class BSSingleElement {
public static int single(int[] arr,int n){
if (arr[0]!=arr[1]) {
return arr[0];
}
if (arr[n-1]!=arr[n-2]) {
return arr[n-1];
}
int low = 2;
int high = n-3;
while (low<=high) {
int mid = low + ((high-low)/2);
if (arr[mid]!=arr[mid+1] && arr[mid]!=arr[mid-1]) {
return arr[mid];
}
if (arr[mid]==arr[mid-1]) {
mid--;
}
if (mid%2==0) {
low = mid+2;
}
else{
high = mid-1;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(single(arr,n));
sc.close();
}
}