본문 바로가기

Algorithm/Programmers

[프로그래머스] 정렬 -k번째 수

*제출 코드

#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 사용법

 

[C++] C++ STL vector 기본 사용법과 예제

Practice makes perfect!

twpower.github.io

2.

나는 새로운 array2를 선언하고 for문을 통해서 push_back해 필요한 부분만 잘라서 저장했는데,

 

그냥 array2= array를 통해서 통으로 배열을 복사하고

sort(array2.begin() + start , array2.begin() + end) 으로 필요한 부분만 정렬,

answer.push_back( start+k ) 를 하면

 

정렬된부분으로 부터 k번째의 수를 반환할 수 있었다.