[정렬] K번째수

yyeahh·2020년 8월 9일
0

프로그래머스

목록 보기
11/35

|| 문제설명 ||

  1. 배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 한다.

  2. commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성하라.

  • array : 배열
  • commands : [i, j, k]를 원소로 가진 2차원 배열
_ array의 길이 : 1 이상 100 이하
_ array의 각 원소 : 1 이상 100 이하
_ commands의 길이 : 1 이상 50 이하
_ commands의 각 원소는 길이 = 3

|| 문제해결과정 ||

- for문(i) : 0 ~ commands.size()
- 새로운 vector변수에 array를 commands[i][0]부터 commands[i][1])까지 저장
- 변수를 sort한 뒤 commands[i][2] 위치의 원소를 answer에 추가

|| 코드 ||

[2020.08.09] 성공

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

using namespace std;

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


[2021.01.31]
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    for(int i = 0; i < commands.size(); i++) {
        int target = commands[i][2]-1;
        vector<int>::iterator start = array.begin()+commands[i][0]-1,
                                end = array.begin()+commands[i][1];
        vector<int> tmp(start, end);
        
        sort(tmp.begin(), tmp.end());
        answer.push_back(tmp[target]);
    }
    return answer;
}

0개의 댓글