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]
.
解法:find函数,返回找到数字的迭代器,然后用distance函数返回下标值,后面就是循环找出相同的个数
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int>::iterator it; vector<int> result; it = find(nums.begin(),nums.end(),target); if(it == nums.end()) { result.push_back(-1); result.push_back(-1); return result; } int i = distance(nums.begin(),it); int n = nums.size(); result.push_back(i); while(*it == nums[++i] && i < n); //确保++i不要数组溢出 result.push_back(i-1); return result; } };