-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearchRange.java
More file actions
executable file
·43 lines (40 loc) · 1015 Bytes
/
searchRange.java
File metadata and controls
executable file
·43 lines (40 loc) · 1015 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
40
41
42
43
/*
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
*/
import java.util.*;
public class searchRange{
public static void main(String[] args) {
int[] A = {5, 7, 7, 8, 8, 10};
int[] res = searchRange(A,8);
System.out.println(res[1]);
}
public static int[] searchRange(int[] A, int target){
int[] res = {-1,-1};
int st = 0;
int ed = A.length;
while(st < ed){
int m = (ed - st)/2 + st;
if(A[m] < target)
st = m + 1;
else
ed = m;
}
if(st >= A.length || A[st] != target) return res;
res[0] = st;
ed = A.length;
while(st < ed){
int m = (ed - st)/2 + st;
if(A[m] > target)
ed = m;
else
st = m + 1;
}
res[1] = ed-1;
return res;
}
}