본문 바로가기

ALGORITHM/OTHER

[c++] K번째수

programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    
    for (int n=0; n<(int)commands.size(); n++) {
        vector<int> newArray(array);
        int i = commands[n][0] - 1;
        int j = commands[n][1];
        int k = commands[n][2] - 1;
        sort(newArray.begin() + i, newArray.begin() + j);
        answer.push_back(newArray[i + k]);
    }
    
    return answer;
}

 

간단한 문제가 생각보다 오래 걸린 이유는..

벡터를 sort 할 때 매번 begin(), end() 만 쓰다보니 sort 의 범위가 [) 라는 것을 간과하고 있었다.

 

벡터에서 end() 이터레이터는 마지막 값보다 한 칸 뒤에 있는 값을 리턴한다.

 

까먹지 말자 @_@