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]
.
思路: 二分法, 找到中间节点和target目标值一样的,然后再由此节点找其临界点.
时间复杂度: O(logN)
public int[] searchRange(int[] nums, int target) {
int[] res={-1,-1};
int len=nums.length;
int left=0,right=len-1;
int mid,temp;
while(left<=right){
mid=(left+right)/2;
if(nums[mid]==target){
temp=mid;
while(temp>0&&nums[temp-1]==target)
temp--;
res[0]=temp;
temp=mid;
while(temp<len-1&&nums[temp+1]==target)
temp++;
res[1]=temp;
break;
}
if(nums[mid]<target)
left=mid+1;
else
right=mid-1;
}
return res;
}