https://leetcode.com/problems/search-for-a-range/
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]
.
二分法代码如下:
public int[] searchRange(int[] A, int target) {
int[] rst = {-1, -1};
if(A==null || A.length==0) return rst;
int left = 0, right = A.length-1;
while(left<=right){
int mid=(left+right)/2;
if(A[mid]==target){
int l = mid;
while(l>0 && A[l-1]==target) l--;
rst[0] = l;
int r = mid;
while(r<A.length-1 && A[r+1]==target) r++;
rst[1] = r;
return rst;
}
else if(A[mid]<target) left = mid+1;
else right = mid-1;
}
return rst;
}
http://fisherlei.blogspot.com/2013/01/leetcode-search-for-range.html