-
Notifications
You must be signed in to change notification settings - Fork 14
/
SearchForRange.java
35 lines (35 loc) · 1.09 KB
/
SearchForRange.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
public class Solution {
public int[] searchRange(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int n = A.length;
int s = 0, e = n - 1;
int[] result = new int[]{-1, -1};
while (s <= e){
int middle = (e + s) /2;
if (A[middle] < target){
s = middle + 1;
}
else if (A[middle] > target){
e = middle - 1;
}
else{
result[0] = middle;
result[1] = middle;
// use binary expand here to optimize to total from O(n) to O(lgn)
for(int i = middle - 1; i >=0; i--){
if (A[i] == target){
result[0] = i;
}
}
for(int i = middle + 1; i < n; i++){
if (A[i] == target){
result[1] = i;
}
}
return result;
}
}
return result;
}
}