LeetCode 34. Search for a Range
Given an array of integers 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]
.
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) {
if(nums.size() == 0)
return vector<int>{-1, -1};
int x = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
int y = upper_bound(nums.begin(), nums.end(), target) - nums.begin();
if(x == nums.size() || nums[x] != target)
return vector<int>{-1, -1};
return vector<int>{x, y-1};
}
};