Algorithm/Programmers
[프로그래머스] K번째 수 : C++
감성적인 개발자
2021. 8. 11. 23:05
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
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer, temp;
for(int i = 0; i < commands.size(); i++){
for(int j = commands[i][0] - 1; j < commands[i][1]; j++){
temp.push_back(array[j]);
}
sort(temp.begin(), temp.end());
answer.push_back(temp[commands[i][2] - 1]);
temp.clear();
}
return answer;
}
commands[0] 에 담긴 [2, 5, 3]을 수행한다 가정하면, array의 2 번째 요소부터 5 번째 요소를 정렬 하고 그 중 3번째 요소를 리턴하면 된다.
2는 commands[0][0]에
5는 commands[0][1]에 존재, 다만 배열은 0 부터 시작하니 commands[0][0] - 1 부터 시작한다.
temp 벡터에 [5, 2, 6, 3]를 넣고 정렬하면 [2, 3, 5, 6] 이되고 여기서 commands[0][2]에 있는 3번째 요소를 리턴한다.