问题链接:https://oj.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].
问题API:public int binarySearch(int[] A, double target)
问题分析:这题利用的是binary search的特质,一旦binary search需要搜索的target不在数组内,Binary search最后head会指向应该插入的位置。于是这题有一个非常取巧的 方法,因为input都是整型数,所以先做一个double的binary search,然后search target – 0.1 和target + 0.1。利用binary search当search不到target最终head会指向target应该插入的地方,得到的range就为(binarySearch(target – 0.1),binarySearch(target + 0.1) - 1);代码如下:
public int binarySearch(int[] A, double target){
int head = 0, tail = A.length - 1;
while(head <= tail){
int mid = (head + tail) / 2;
if((double)A[mid] == target)
return mid;
else if((double)A[mid] < target)
head = mid + 1;
else
tail = mid - 1;
}
return head;
}
public int[] searchRange(int[] A, int target) {
int left = binarySearch(A, target - 0.1);
int[] res = new int[]{-1, -1};
if(left == A.length || A[left] != target)//这个是判断的就是target是否不在这个数组里,是的话就没有range了。
return res;
res[0] = left;
int right = binarySearch(A, target + 0.1);
res[1] = right - 1;
return res;
}