- 문제 풀이
"정렬"을 사용하는 문제였다.
sort함수를 사용하기 위해 #include <algorithm>을 불러왔다.
이후 새로운 배열을 만들기 위한 vector arr만 매 for문 마다 선언하여 주어진 문제를 해결하면 되는 간단한 문제이다.
- 코드
처음 작성한 풀이는 다음과 같다.
## 기억해야 할 것 ##
1. vector에 임의의 원소를 넣을 땐 push가 아니라 push_back()을 사용한다.
2. 배열 arr[]을 sort 할때는 sort(arr, arr+N); 의 형태이지만,
vector arr을 sort 할때는 sort(arr.begin(), arr.end())를 사용한다.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
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> arr;
int n = commands[i][1]-commands[i][0]+1;
for(int j=commands[i][0]-1; j<commands[i][1]; j++) {
arr.push_back(array[j]);
}
sort(arr, arr+n);
answer.push_back(array[commands[i][2]-1]);
}
return answer;
}
수정을 거쳐 최종적으로 작성한 풀이는 다음과 같다.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> solution(vector<int> array1, vector<vector<int>> commands) {
vector<int> answer;
for(int i=0; i<commands.size(); i++) {
vector<int> arr;
for(int j=commands[i][0]-1; j<commands[i][1]; j++) {
arr.push_back(array1[j]);
}
sort(arr.begin(), arr.end());
answer.push_back(arr[commands[i][2]-1]);
}
return answer;
}
'프로그래머스' 카테고리의 다른 글
| 가장 큰 수 - 프로그래머스, c++ (0) | 2023.01.28 |
|---|---|
| 프린터 - 프로그래머스, c++ (0) | 2023.01.27 |
| 기능개발 - 프로그래머스, c++ (0) | 2023.01.18 |
| 위장 - 프로그래머스, c++ (0) | 2023.01.13 |
| 전화번호 목록 - 프로그래머스, c++ (0) | 2023.01.12 |