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对比,如果相等将次下标存入results中,继续扫描找出第一个不等于target的位置并把该位置减1存入result中。如果数组扫描完后results中有一个元素,则该数组的最后一个元素一定与target相等,把最后一个元素的下标存入results中,如果results为空返回[-1, -1]。(Time:8ms)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> results;
for(int i=0; i<nums.size(); ++i)
{
if(nums[i]==target && results.size()==0)
{
results.push_back(i);
}
else if(nums[i] != target && results.size()==1)
{
results.push_back(i-1);
return results;
}
}
if(results.size()==1)
{
results.push_back(nums.size()-1);
}
else if(results.size()==0)
{
results={-1, -1};
}
return results;
}
};