题目:
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].
题意:
给定一个数组,给定一个目标值,找出数组中的下标的区间,这个区间里的元素都等于目标值。
思路:
采用lower_bound和upper_bound
代码如下:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result = {-1, -1};
if(nums.size() == 0) {
return result;
}
auto iter1 = lower_bound(nums.begin(), nums.end(), target);
auto iter2 = upper_bound(nums.begin(), nums.end(), target);
if(iter1 == nums.end() || *iter1 != target)return result;
result[0] = iter1 - nums.begin();
result[1] = iter2 - nums.begin() - 1;
return result;
}
};