public class Solution {
public int[] searchRange(int[] A, int target) {
int start=0, end=A.length-1, mid, pivot=0;
while(start<=end){
mid = (start+end)/2;
if(A[mid] == target){
pivot = mid;
break;
}else if(target > A[mid])
start=mid+1;
else
end=mid-1;
}
<span style="background-color: rgb(255, 204, 204);"> if(A[pivot]!=target)
return new int[]{-1,-1};</span>
int start1=0, end1=pivot, mid1;
while(start1 <= end1){
mid1 = (start1+end1)/2;
if(A[mid1] == target)
end1=mid1-1;
else
start1=mid1+1;
}
int new_low = <span style="background-color: rgb(255, 255, 51);">start1</span>;
int start2=pivot+1, end2 = A.length-1, mid2;
while(start2 <= end2){
mid2 = (start2+end2)/2;
if(A[mid2] == target)
start2=mid2+1;
else
end2=mid2-1;
}
int new_high = <span style="background-color: rgb(255, 255, 51);">end2</span>;
return new int[]{new_low,new_high};
}
}
分析:数组是有序的,找到一个值两边的index。O(log n) 暗示二叉搜索,这里考点就是如何设置Middle
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]
.