본문 바로가기
코딩테스트/프로그래머스(lv1)

[프로그래머스 Level 1] K 번째 수 (C++)

by 볼링치는 개발자 2021. 1. 24.
반응형

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

K 번째 수 문제

구현 방법

입력 배열은 array와 commands인데, commands가 [1,5,3]으로 주어지면 이는 array를 1번째 원소부터 5번째 원소들을 담고 정렬하여 그중 3번째 수를 뽑는 문제이다.

 

간단하게 commands의 개수 만큼 반복하고, 2번째 for문은 commands의 첫 번째 원소부터 두 번째 원소만큼 반복된다.

이때 array의 해당 index에 있는 값을 하나의 배열에 담아주고, 해당 배열을 정렬하고 commands의 마지막 원소인 K번째 수를 꺼내서 답으로 제출하면 된다.

 

해당 로직은 아래와 같이 구현했다.

소스코드

#include <bits/stdc++.h>
using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    //주어진 commands 개수 만큼 반복
    for(int i = 0 ; i < commands.size(); i++) {
        //commands에서 주어진 i부터 j까지 잘라서 담을 배열 temp
        vector<int> temp;

        //입력 배열 array를 commands의 첫번째 원소 부터, 두번째 원소까지 담는다 
        for(int j = commands[i][0]-1; j < commands[i][1] ;j++) {
            temp.push_back(array[j]);
        }
        //정렬 하고, commands의 마지막 원소인 K번째 수를
        // array를 잘라서 담아놓은 temp에서 꺼낸다
        sort(temp.begin(), temp.end());
        answer.push_back(temp[commands[i][2]-1]);
    }
    return answer;
}
반응형

댓글