#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
int i,j,k;
for (int t=0;t<commands.size();++t){
i = commands[t][0]-1;
j = commands[t][1];
k = commands[t][2]-1;
vector<int>tmp;
for (int s = i; s < j; ++s){
tmp.push_back(array[s]);
}
sort(tmp.begin(),tmp.end());
answer.push_back(tmp[k]);
}
return answer;
}
- 나의 풀이
i, j, k를 분리해놓고,
tmp 벡터에 i~j까지 슬라이싱 한 후,
sort로 정렬해서 k번째 값을 읽어 왔다.
- 다른 사람들의 풀이
파이썬에는 슬라이싱이 있지만, C++에서는 sort를 하면서 slicing이 되는 것처럼 구현한 것을 봤다.
그렇게 하면 이중 for문 없이도 하나의 반복문으로 해결할 수 있게 된다.
for(int i = 0; i < commands.size(); i++) {
temp = array;
sort(temp.begin() + commands[i][0] - 1, temp.begin() + commands[i][1]);
answer.push_back(temp[commands[i][0] + commands[i][2]-2]);
}
k-1번째는 → temp[i-1 + (k-1)]가 되니까 temp[i + k - 2]로 바로 k위치에 있는 원소를 찾을 수 있게 된다.
ex. i가 2라면 인덱스 상에서는 1이니까 (2-1)이고, k가 3이라면 인덱스 상에서는 2번째에 있으니까,
시작 위치의 인덱스 (i-1)에서 + k 위치의 인덱스 (k-1)를 더해서 이동하면 되는 것이다.
'PS > Programmers' 카테고리의 다른 글
| [SQL] SQL NULL값인 컬럼 처리하기 (IFNULL) (0) | 2026.01.07 |
|---|---|
| [프로그래머스/C++] Level1 - 2016년 풀이 (0) | 2025.12.07 |
| [프로그래머스/C++] 가장 가까운 같은 글자 (lv1) (0) | 2025.10.21 |
| [프로그래머스/C++] 알고리즘 고득점 키트 - 베스트앨범 (1) | 2025.07.04 |
| [프로그래머스/C++] 알고리즘 고득점 키트 - 체육복 (0) | 2025.05.21 |