개발하는 kim-hasa

[c++][프로그래머스] K번째수 본문

Algorithm/Programmers(c++)

[c++][프로그래머스] K번째수

kim-hasa 2021. 7. 27. 14:19

https://programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

sort를 위해 #include <algorithm> 을 추가합니다.

 

배열에서 특정 index만큼 자른 후 자른 배열의 특정 index를 추출하는 문제입니다.

 

특정 index 범위만큼을 잘라서 slice 벡터 배열에 넣은 후, 정렬하고 특정 index를 정답 벡터에 넣습니다.

 

slice 배열을 초기화 하고 반복합니다.

 

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    int first;  // command 배열의 i번째 숫자
    int last;   // command 배열의 j번째 숫자
    int index;  // command 배열 정렬 후 k번째 숫자
    vector<int> slice;  // 자른 배열
    
    for(int i=0; i < commands.size(); i++)
    {
        first = commands[i][0];
        last = commands[i][1];
        index = commands[i][2]; // 숫자 넣기
        
        for(int j=first-1; j<last; j++) // slice배열에 넣기 위해
        {
            slice.push_back(array[j]);
        }
        
        sort(slice.begin(), slice.end());   // 정렬
        
        answer.push_back(slice[index-1]);
        
        slice.clear();
    }
    
    return answer;
}

※ 코드가 지저분할 수 있습니다.