하루하루 꾸준히, 인생은 되는대로

정렬

Find First and Last Position of Element in Sorted Array C++

긤효중 2022. 12. 25. 23:27

백준만 풀다가 내년부터는 리트코드를 쭉 풀어보려고 한다.(이유는 Discuss 탭의 다양하고 알찬 정보들 보기)

Discuss에서 시간 복잡도나, 다른 사람의 생각을 볼 수 있다는 게 큰 장점인 것 같기도 하다.

 

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/?envType=study-plan&id=algorithm-ii 

 

Find First and Last Position of Element in Sorted Array - LeetCode

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 the array, return [-1, -1]. You must write a

leetcode.com

이분 탐색 문제에서 lower_bound,upper_bound를 이용해 해결했다.

 [5,7,7,8,8,10], target = 8

일떄, target의 시작과 target의 마지막 인덱스를 찾는 문제이다.

 

 

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> ans;
        if(nums.size() == 0 || (nums[nums.size()-1] < target)){
            ans.push_back(-1);
            ans.push_back(-1);
            return ans;
        }
        
        int firstIndex = lower_bound(nums.begin(),nums.end(),target) - nums.begin();
        if(nums[firstIndex] != target){
            ans.push_back(-1);
            ans.push_back(-1);
        }
        else{
            ans.push_back(firstIndex);
            int lastIndex = upper_bound(nums.begin(),nums.end(),target) - nums.begin();
            lastIndex -= 1;
            ans.push_back(lastIndex);
        }
        return ans;
    
    }
};

 

'정렬' 카테고리의 다른 글

2차원 배열에서 이분 탐색 사용하기  (0) 2022.12.27
백준 20551 Sort 마스터 배지훈의 후계자  (0) 2022.08.06
백준 2693 C언어  (0) 2021.10.08
백준 11399 C언어  (0) 2021.10.04
백준 1026번 C언어  (0) 2021.10.01