티스토리 뷰
기본적인 배열 사용법과 sort 사용하기 문제.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
for(auto input : commands) {
vector<int> sliceArray;
for(int i = input[0]-1; i < input[1]; i++) {
sliceArray.push_back(array[i]); //배열 잘라서 새로운 배열 생성
}
sort(sliceArray.begin(),sliceArray.end());
answer.push_back(sliceArray[input[2]-1]);
}
return answer;
}
sliceArray를 생성해서 범위만큼 loop로 넣어줌
sliceArray를 sort하고 해당하는 위치의 값을 answer에 넣어준다.
원래 하려던 방법은 sliceArray로 자르지 않고 sort 범위를 직접 정해주는 방법이었는데,
이렇게 되면 기존 array를 복사해야하기 때문에 사실상 시간은 더 걸리겠단 생각을 했다.
코드 직관성도 떨어질테고?
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
vector<int> temp;
for(auto input : commands) { // index 1~4
temp = array;
sort(temp.begin()+input[0]-1,temp.begin()+input[1]);
answer.push_back(temp[input[0]+input[2]-2]);
}
return answer;
}
그래도 함 써봤다.
temp.begin()으로 시작안하고 temp로 써서 한참 애먹었따 ㅋㅋ;;
'■ 알고리즘 > ◻ Programmers' 카테고리의 다른 글
[C++]H-Index (0) | 2022.11.10 |
---|---|
[C++]가장 큰 수 (0) | 2022.11.09 |
[C++] 위장 (0) | 2022.11.09 |
[C++] 전화번호 목록 (0) | 2022.11.09 |
[C++] 폰켓몬 (0) | 2022.11.08 |