Given an array of integers sorted in ascending order, 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]
.
AC代码如下:
class Solution {
public://先用二分查找找出这个数,再由这个数往左、往右查找边界(非最优,最坏情况下为O(n))
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret;
int left=0;
int right=nums.size()-1;
int mid;
while(left<=right){
mid=(left+right)/2;
if(nums[mid]==target)
break;
else if(nums[mid]<target)
left=mid+1;
else
right=mid-1;
}
if(left>right){
ret.push_back(-1);
ret.push_back(-1);
return ret;
}else{
int i=mid,j=mid;
int length=nums.size();
for(;i>=0;i--){
if(nums[i]!=target)
break;
}
for(;j<length;j++){
if(nums[j]!=target)
break;
}
ret.push_back(i+1);
ret.push_back(j-1);
return ret;
}
}
};