Search for a Range
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然后再向两边查找的话,就会超时,需要用两次二分。
第一次二分和第二次二分的区别在等号的位置,注意~~
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res;
res.push_back(-1);
res.push_back(-1);
int n=nums.size();
if(n==0)return res;
if(nums[n-1]<target || nums[0]>target) return res;
int left=0,right=n-1;
while(left<right-1)
{
int mid=(left+right)/2;
if(nums[mid]>=target)right=mid;
if(nums[mid]<target)left=mid;
}
if(nums[left]==target) res[0]=left;
else if(nums[right]==target) res[0]=right;
else return res;
left=0;right=n-1;
while(left<right-1)
{
int mid=(left+right)/2;
if(nums[mid]>target)right=mid;
if(nums[mid]<=target)left=mid;
}
if(nums[right]==target) res[1]=right;
else if(nums[left]==target) res[1]=left;
else return res;
return res;
}
};