-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search for a Range
42 lines (42 loc) · 1.44 KB
/
Search for a Range
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
public class Solution {
public int[] searchRange(int[] A, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case.
/*implementing special binary search*/
int result[] = {-1, -1};
if(A.length == 0) return result;
int left = 0, right = A.length-1;
return helpler(result, A, target, left, right);
}
private int[] helpler(int[] result, int[] A, int target, int left, int right)
{
if(left>right)
return result;
int mid = (left+right)/2;
if(target>A[mid])
return helpler(result, A, target, mid+1, right);
else if(target<A[mid])
return helpler(result, A, target, left, mid-1);
else{
if(result[0] == -1 && result[1] == -1)
{
result[0] = mid;
result[1] = mid;
int[] start = helpler(result, A, target, left, mid-1);
int[] end = helpler(result, A, target, mid+1, right);
result[0] = start[0];
result[1] = end[1];
return result;
}
else if(mid<result[0])
{
result[0] = mid;
return helpler(result, A, target, left, mid-1);
}
else
{
result[1] = mid;
return helpler(result, A, target, mid+1, right);
}
}
}
}