二分搜索,在找最左端,要找的目标值小于target,所以最后必定left指向最左端,right指向最左端的前一个数字,同理,最右端
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n=nums.size();
int left=0,right=n-1,mid;
int L,R;
vector<int> ans{-1,-1};
bool find=false;
while(left<=right)
{
mid=(left+right)>>1;
if(nums[mid]==target)
{
find=true;
break;
}
else if(nums[mid]>target)
right=mid-1;
else
left=mid+1;
}
if(!find)
return ans;
left=0,right=mid;
while(left<=right)
{
mid=(left+right)>>1;
if(nums[mid]==target)
right=mid-1;
else if(nums[mid]<target)
left=mid+1;
}
L=left;
left=mid,right=n-1;
while(left<=right)
{
mid=(left+right)>>1;
if(nums[mid]==target)
left=mid+1;
else if(nums[mid]>target)
right=mid-1;
}
R=right;
ans[0]=L;
ans[1]=R;
return ans;
}
};