K번째수

NJW·2021년 8월 25일
0

코테

목록 보기
79/170

들어가는 말

배열이 두 개 주어진다. 두 번째 배열의 i부터 j까지 첫 번째 배열에서 가지고 와서 오름차순으로 정렬한 뒤 k번째 숫자를 반한하는 문제이다.

코드 설명

정렬 문제 답게 오름차순으로 정렬하는 방법이 나왔다. 그리고 정렬에서 곤란에 처했다. 정렬을 못해서 버벅거린 게 아니다. 케이스 별로 정렬을 해주어야 하는데, sort는 전부를 정렬한 것.
첫 번째 케이스를 정렬하면 '2, 3, 5, 6'이 된다. 그리고 두 번째 케이스를 넣어서 정렬하면 '2, 3, 5, 6, 6'이 되고 그렇다면 세 번째 케이스는? '1, 2, 2...'이렇게 된다. 첫 번째 숫자부터 전부 정렬을 하기 때문이다. 그렇기에 정답을 미리 넣어주고 clear함수로 배열을 지워주어야 한다.

코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool cmp(int a, int b){
    return a < b;
}

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    vector<int> num;
    
    for(int i=0; i<commands.size(); i++){
        for(int j=commands[i][0]-1; j < commands[i][1]; j++){
            num.push_back(array[j]);
        }
        sort(num.begin(), num.end(), cmp);
        answer.push_back(num[commands[i][2]-1]);
        num.clear();

    }
    
    return answer;
}

P.s

저렇게 이중 반복문을 쓰지 않고 푸는 법을 발견했다. 다른 사람들의 풀이인데, sort에 바로 commands[i][0]-1과 command[i][1]-1을 집어넣는 것. 다음 answer.push_back에도 위의 것과 비슷하게 해준다.

sort(temp.begin() + commands[i][0] - 1, temp.begin() + commands[i][1]);
answer.push_back(temp[(commands[i][0]-1) + (commands[i][2]-1)]);

https://programmers.co.kr/learn/courses/30/lessons/42748/solution_groups?language=cpp&type=all
제일 첫 번째 문제

profile
https://jiwonna52.tistory.com/

0개의 댓글