*제출 코드
#include <string>
#include <vector>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
int start,end,k;
for(int i=0; i<commands.size(); i++){
start = commands[i][0]-1;
end = commands[i][1]-1;
k = commands[i][2]-1;
vector<int> array2;
for(int j=start; j<=end; j++){
array2.push_back(array[j]);
}
for(int j=1; j<array2.size(); j++){
int key = array2[j];
int s;
for (s =j-1 ; s>=0 && array2[s]>key; s-- )
array2[s+1] = array2[s];
array2[s+1]= key;
}
answer.push_back(array2[k]);
}
return answer;
}
*review
1.
삽입 정렬을 구현한 아래 코드를
for(int j=1; j<array2.size(); j++){
int key = array2[j]; int s;
for (s =j-1 ; s>=0 && array2[s]>key; s-- )
array2[s+1] = array2[s];
array2[s+1]= key;
}
<algorithm> 헤더를 include 하면
sort(array2.begin(), array2.end()) 한 줄로 구현 할 수있다.
사실 이 헤더와 sort함수를 알고 있었는데 정렬에 대한 문제라서 사용하지 않았는데, 사용해도 되나보다.
=>쓸 수 있는 stl은 열심히 활용하자^^;
- sort 함수 사용법
[Algorithm] C++에서 sort 함수를 이용해 정렬하기
Practice makes perfect!
twpower.github.io
- vector stl 사용법
twpower.github.io
2.
나는 새로운 array2를 선언하고 for문을 통해서 push_back해 필요한 부분만 잘라서 저장했는데,
그냥 array2= array를 통해서 통으로 배열을 복사하고
sort(array2.begin() + start , array2.begin() + end) 으로 필요한 부분만 정렬,
answer.push_back( start+k ) 를 하면
정렬된부분으로 부터 k번째의 수를 반환할 수 있었다.
'Algorithm > Programmers' 카테고리의 다른 글
| [프로그래머스] 전화번호 목록 (0) | 2020.03.24 |
|---|---|
| [프로그래머스] - 타겟넘버 (0) | 2020.03.18 |
| [프로그래머스] 가장 큰 수 (0) | 2020.03.11 |
| [프로그래머스] 이분탐색 - 예산 (0) | 2020.03.04 |