
count가 commands의 각 요소를 참조한다.tmp를 array[i]~array[j] 범위 값으로 할당한다.tmp[k] 값을 answer에 삽입한다.#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer, tmp;
int i, j, k;
for (auto &count : commands) {
i = count[0] - 1;
j = count[1] - 1;
k = count[2] - 1;
tmp.assign(array.begin() + i, array.begin() + j + 1);
sort(tmp.begin(), tmp.end());
answer.push_back(tmp[k]);
}
return answer;
}
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands)
{
vector<int> answer, tmp;
int i, j, k;
// 범위 기반 for문을 사용해 2차원벡터 commands의 각 원소(1차원벡터)을
// 1차원벡터 count가 하나씩 참조한다.
// count의 각 원소에서 1을 뺀 값을 변수 i, j, k에 대입한다.
// 배열의 인덱스는 0부터 시작하므로 각각 1씩 빼준 것이다.
for (vector<int>& count : commands)
{
i = count[0] - 1;
j = count[1] - 1;
k = count[2] - 1;
// array의 i번째부터 j번째 사이에 포함된 원소를 벡터 tmp에 넣어준다.
// assign(begin, end) 함수는 begin부터 end 직전 원소까지 옮겨주므로 j에 1을 더함
tmp.assign(array.begin() + i, array.begin() + j + 1);
// sort(v.begin(), v.end()) 함수는 벡터 원소 전체를 정렬한다.
// 따로 지정해 주지 않으면 기본으로 오름차순으로 정렬한다.
sort(tmp.begin(), tmp.end());
// 정렬한 tmp의 인덱스 k의 숫자를 벡터 answer에 넣고 반환한다.
answer.push_back(tmp[k]);
}
// 정답 확인용 출력
for (int& val : answer)
{
cout << val << " ";
}
return answer;
}
int main()
{
solution({1, 5, 2, 6, 3, 7, 4}, {{2, 5, 3,}, {4, 4, 1}, {1, 7, 3}});
return 0;
}
참고
C++ assign()
C++ sort()
범위기반 for문
https://boycoding.tistory.com/210