최대 1 분 소요

Question

Q


Solution

  • vector에 있는 수를 commands.size()만큼 정렬하여 사용할 것이기 때문에 vector를 복제한다.
  • commands로부터 i,j,k를 구하고 해당 되는 숫자만 복제된 temp에 넣는다.
  • 새로 숫자가 채워진 temp를 정렬하고 k번째 숫자를 answer에 넣는다.

  • 다른 풀이 : 다른 풀이에선 i ~ j 사이 부분만 정렬을 실행하고 k를 찾아 코드가 더 간략화 가능하였다. begin()을 i, j, k에 각각 더해서 구하는 방식이였다.

Cord

#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> temp;
        int from = commands[i][0] - 1;
        int to = commands[i][1];
        int k = commands[i][2] - 1;

        for(int j = 0; j < array.size(); j++)
        {
            if (j >= from && j < to)
            {
                temp.push_back(array[j]);
            }
            else if (j >= to) { break; }
        }
        
        sort(temp.begin(), temp.end());
        answer.push_back(temp[k]);
    }
    
    return answer;
}

Result

Result