描述:
Given an array of integers nums sorted in ascending order, 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
解题思路:
本题的解法是将vector中的每一个元素与target进行比对,当元素与target相等时将下标记录下来。
C++代码:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target)
{
vector<int>res;
vector<int>result;
vector<int>res_copy(2,-1);
int len= nums.size();
for(int i = 0;i<len;i++)
{
if(nums[i]==target)
{
res.push_back(i);
}
}
if(res.size()==0)
{
return res_copy;
}
if(res.size()==1)
{
res.push_back(res[0]);
return res;
}
if(res.size()==2)
{
return res;
}
if(res.size()>2)
{
result.push_back(res[0]);
result.push_back(res[res.size()-1]);
return result;
}
return res;
}
};
运行结果: