April 20, 2021
https://programmers.co.kr/learn/courses/30/lessons/42748
문제
배열 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 함수를 작성해주세요.
딱히 풀이를 안적어도 될 정도로 단순한 문제였다. 나는 모든 명령어에 대해서 부분배열을 만들고, 만든 부분배열을 정렬한 뒤 인덱스에 맞게 값을 출력해주었다.
{% raw %}
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
for (auto command : commands) {
int start = command[0] - 1;
int end = command[1];
int target = command[2];
vector<int> subArray(array.begin() + start, array.begin() + end);
sort(subArray.begin(), subArray.end());
answer.push_back(subArray[target - 1]);
}
return answer;
}
{% endraw %}