Scribbling

[C++] lower_bound, upper_bound 본문

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};
    }
};

 

'Computer Science > C++' 카테고리의 다른 글

[C++] Chapter 2: Types  (0) 2023.08.21
[C++] Load Balancing  (0) 2023.08.19
[C++] isalnum, tolower  (0) 2023.08.18
[C++] LeetCode 128. Longest Consecutive Sequence  (0) 2023.08.18
[C++] LeetCode 238. Product of Array Except Self  (0) 2023.08.18