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].
主要是二分的思想,在左右边界判定的时候,主要就是IF判断语句的等号取的位置不同,
返回的值一个是left,一个是right。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int>ans(2,-1);
int l=0,r=nums.size()-1,fla=0;
while(l<=r){
int mid=(l+r)/2;
if(nums[mid]==target){fla=1;}
if(target<=nums[mid])
r=mid-1;
else
l=mid+1;
}
if(fla)ans[0]=l;
l=0,r=nums.size()-1,fla=0;
while(l<=r){
int mid=(l+r)/2;
if(nums[mid]==target){fla=1;}
if(target<nums[mid])
r=mid-1;
else
l=mid+1;
}
if(fla)ans[1]=r;
return ans;
}
};