-
Notifications
You must be signed in to change notification settings - Fork 33
/
Search for a Range.java
57 lines (52 loc) · 1.39 KB
/
Search for a Range.java
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
46
47
48
49
50
51
52
53
54
55
56
57
public class Solution {
// DO NOT MODIFY THE LIST
ArrayList<Integer> ans = new ArrayList<>();
public ArrayList<Integer> searchRange(final List<Integer> a, int b) {
ans.add(-1);
ans.add(-1);
findRange(a, 0, a.size()-1, b);
return ans;
}
public void findRange(List<Integer> a, int start, int end, int b) {
int mid = 0;
while (start <= end) {
mid = (start + end)/2;
if (a.get(mid) == b) {
int low = findExtreme(a, start, mid-1, b, true);
int high = findExtreme(a, mid+1, end, b, false);
ans.set(0, low == -1 ? mid : low);
ans.set(1, high == -1 ? mid : high);
return;
}
else if (a.get(mid) < b) {
start = mid+1;
}
else {
end = mid-1;
}
}
}
public int findExtreme(List<Integer> a, int start, int end, int b, boolean left) {
int idx = -1;
int mid = 0;
while (start <= end) {
mid = (start + end)/2;
if (a.get(mid) == b) {
idx = mid;
if (left) {
end = mid-1;
}
else {
start = mid+1;
}
}
else if (a.get(mid) < b) {
start = mid+1;
}
else {
end = mid-1;
}
}
return idx;
}
}