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]
.
解题思路:
求一个已经排好序的数组中指定重复元素的下标。要求复杂度为O(log n)。最直观的解法就是二分法,在这个基础上找到下标即可。代码如下:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res;
if(nums.size()==0) return res;
int low=0;
int high=nums.size()-1;
while(low<=high)
{
int mid=(low+high)/2;
if(nums[mid]<target)
{
low=mid+1;
}
else if(nums[mid]>target)
{
high=mid-1;
}
else
{
int flag=0;
for(int i=low;i<=high;i++)
{
if((nums[i]==target&&flag==0)||(nums[i]==target&&i==high))//找到第一个指定元素或者子序列的最后一个元素为指定元素我们就入数组
{
res.push_back(i);
flag=1;
}
if(nums[i]!=target&&res.size()>0)//找到第一个不等于指定元素的值,也就是说重复元素的下一位下标找到
{
if((i-1)!=res[0])
res.push_back(i-1);
break;
}
}
break;
}
}
if(res.size()==0)//没有指定元素出现
{
res.push_back(-1);
res.push_back(-1);
}
if(res.size()==1)
{
res.push_back(res[0]);
}
return res;
}
};