Question:
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]
.
分析:
两次二分法,即可达到log(n)的要求,但是这里的二分法有些区别。二分判断只设计两个条件:1.大于/小于 2.else。举例而言,如果求左边的起始位置,那么 target>A[mid]--> left=mid+1,这样一来,左边的指针除非到左后跳出循环的一步,否则不能指向target,那么最终,left一定指向第一个target起始值,否则array里不存在target。右起始位置同理。
Code:
public class Solution {
public int[] searchRange(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int left = 0, right = A.length-1;
int[] res = {-1, -1};
if(A==null || A.length==0) return res;
while(left <= right){
int mid = (left+right)/2;
if(target > A[mid]) left = mid+1;
else right = mid-1;
}
if(left<0 || left>=A.length || A[left]!=target) return res;
res[0] = left;
right = A.length-1;
while(left <= right){
int mid = (left+right)/2;
if(target < A[mid]) right = mid-1;
else left = mid+1;
}
res[1] = right;
return res;
}
}
小结:
两次二分法的巧妙运用,很适合钻研透彻以深入了解二分法。