Computer Science/C++
[C++] lower_bound, upper_bound
focalpoint
2023. 8. 18. 11:20
LeetCode 34. Find First and Last Position of Element in Sorted Array
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
Find First and Last Position of Element in Sorted Array - LeetCode
Can you solve this real interview question? Find First and Last Position of Element in Sorted Array - Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in t
leetcode.com
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.size() == 0) {
return {-1, -1};
}
int i = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
int j = upper_bound(nums.begin(), nums.end(), target) - 1 - nums.begin();
if (i < nums.size() && nums[i] == target) {
return {i, j};
}
return {-1, -1};
}
};