💻 K번째수
분류 : Sort (정렬)
사용 언어 : C++
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
이 문제는 배열을 자르는 코드, 정렬하는 코드, 랜덤 액세스를 할 수 있어야 한다.
Algorithm의 Sort를 통하여 정렬을 한다.
#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> sorting(array.begin() + commands[i][0] - 1, array.begin() + commands[i][1]);
// sorting용 vector생성 (범위 array의 index부터 )
sort(sorting.begin(), sorting.end()); // Algorithm의 Sort를 통하여 오름차순으로 정렬
answer.push_back(sorting[--commands[i][2]]); // 랜덤 액세스 참조하여 push_back
}
return answer;
}
/*
정확성 테스트
테스트 1 〉 통과 (0.01ms, 3.89MB)
테스트 2 〉 통과 (0.01ms, 3.93MB)
테스트 3 〉 통과 (0.01ms, 3.88MB)
테스트 4 〉 통과 (0.01ms, 3.94MB)
테스트 5 〉 통과 (0.01ms, 3.94MB)
테스트 6 〉 통과 (0.01ms, 3.93MB)
테스트 7 〉 통과 (0.02ms, 3.95MB)
채점 결과
정확성: 100.0
합계: 100.0 / 100.0
*/
시간 복잡도 : n
범위를 다른 Vector로 옮긴 후 Algorithm의 Sort를 통하여 정렬 후 추출