coding_test/programmers

lv1 / K번째 수 / C++

CodeJin 2021. 12. 20. 00:40

https://programmers.co.kr/learn/courses/30/lessons/42748?language=cpp 

 

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

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

programmers.co.kr

전체 배열을 주어주고, 구간을 잘라 정렬하고, 거기서 k번째 수를 찾는 문제.

 

구간을 복사하여, 주어진대로 한다.

 

#include <vector>
#include <algorithm>
using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    vector<vector<int>>::iterator commandIter = commands.begin();
    vector<int> copyArray;

    for (; commandIter != commands.end(); ++commandIter) {
        copyArray.assign(array.begin() + commandIter->at(0) - 1, array.begin() + commandIter->at(1));
        sort(copyArray.begin(), copyArray.end());
        answer.push_back(copyArray[commandIter->at(2) - 1]);
    }
    return answer;
}

이 문제를 풀고 나서 좀 더 간결하게 풀 방법이 없을까 했다가, 다른 분의 풀이를 참고하여 다시 풀어 보았다.

//second sol
#include <vector>
#include <algorithm>
using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    vector<int> copyArray;

    for (auto& command : commands) {
        copyArray.assign(array.begin() + command[0] - 1, array.begin() + command[1]);
        sort(copyArray.begin(), copyArray.end());
        answer.push_back(copyArray[command[2] - 1]);
    }
    return answer;
}