- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
- 34. Find First and Last Position
Share
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]
AC代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res;
auto it1 = lower_bound(nums.begin(), nums.end(), target);
auto it2 = upper_bound(nums.begin(), nums.end(), target);
if (it1 == it2) {
res.push_back(-1);
res.push_back(-1);
}
else {
res.push_back(it1 - nums.begin());
res.push_back(it2 - nums.begin() - 1);
}
return res;
}
};
总结
学习了lower_bound和upper_bound两个STL函数
网友评论