Your algorithm's runtime complexity must be in the order of O(log n).
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4]
Java Solutions:
1.because of O(logn), so we should consider about binary search, so how to apply binary search to find the low bound and high bound? We can make target -0.5 for searching low bound and target+0. 5 for the high bound. Be careful the corner case.
public class Solution {
public int[] searchRange(int[] A, int target) {
if(A==null||A.length==0)
return null;
int[] results={-1,-1};
int low=binarySearch(A,target-0.5);
if(low>=A.length||A[low]!=target)
return results;
results[0]=low;
results[1]=binarySearch(A,target+0.5)-1;
return results;
}
private int binarySearch(int[] A,double target){
int low=0;
int high=A.length-1;
while(low<=high){
int mid=low+(high-low)/2;
if(target==A[mid])
return mid;
if(target<A[mid])
high=mid-1;
else
low=mid+1;
}
return low;
}
}
2. Or
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] results = {-1, -1};
int low=binarySearch(A,target);
if (A[low] != target)
return results;
results[0] = low;
// Remember the "target+1"
int high=binarySearch(A,target+1);
high = A[high] == target ? high : high - 1;
results[1] = high;
return results;
}
private int binarySearch(int[] A,int target){
int low = 0;
int high = A.length - 1;
while (low < high) {
int mid = low+(high - low) / 2;
if (A[mid] < target)
low = mid + 1;
else
high = mid;
}
return low;
}
}