Programmers/Level 1

C++ / 프로그래머스 / K번째수

GitHubSeob 2021. 8. 15. 20:11

문제

https://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

 

문제풀이

array의 i번째 수부터 j번째 숫자까지 자르고, 자른 숫자를 오름차순으로 정렬하고 k번째 숫자를 return 하는 문제이다.

i는 commands의 행수만큼, 배열은 0부터 시작이므로 commands[i][0]-1부터 commands[i][1]-1까지 int형 벡터 number에 push 한다.

숫자를 i번째부터 j번째까지 잘랐으므로 sort로 오름차순으로 정렬한다.

정렬이 끝났으면 number의 commands[i][2]-1번째 수를 답에 push 한다.

 

 

 

코드

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

using namespace std;

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

    return answer;
}