-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchRangeSolution.java
57 lines (55 loc) · 1.62 KB
/
SearchRangeSolution.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
import java.util.*;
public class SearchRangeSolution {
/**
*@param A : an integer sorted array
*@param target : an integer to be inserted
*return : a list of length 2, [index1, index2]
*/
public static ArrayList<Integer> searchRange(ArrayList<Integer> A, int target) {
// write your code here
int left = 0;
int right = A.size() - 1;
ArrayList<Integer> res = new ArrayList<Integer>();
if(A == null || A.size() == 0){
res.add(-1);
res.add(-1);
return res;
}
//A.toArray();
while(left <= right){
int mid = (left+right)/2;
System.out.println(mid);
if(A.get(mid) == target){
if(mid >= 1 && A.get(mid-1) == target){
res.add(mid-1);
res.add(mid);
}
if(mid < A.size() - 1 && A.get(mid+1) == target){
res.add(mid);
res.add(mid+1);
}
else{
res.add(mid);
res.add(mid);
}
return res;
}
else if(A.get(mid) > target){
right--;
}
else{
left++;
}
}
res.add(-1);
res.add(-1);
return res;
}
public static void main(String args[]){
//int[] A = {-3,1,1,-3,5};
ArrayList<Integer> A = new ArrayList<Integer>();
A.add(1);
//Integer a = new Integer(1);
System.out.println(searchRange(A , 1));
}
}