-
[정렬] K번째수Study/Coding Test 2021. 2. 1. 21:32
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
문제 설명
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
- array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
- 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
- 2에서 나온 배열의 3번째 숫자는 5입니다.
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한사항
- array의 길이는 1 이상 100 이하입니다.
- array의 각 원소는 1 이상 100 이하입니다.
- commands의 길이는 1 이상 50 이하입니다.
- commands의 각 원소는 길이가 3입니다.
입출력 예
array commands return [1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3] 입출력 예 설명
[1, 5, 2, 6, 3, 7, 4]를 2번째부터 5번째까지 자른 후 정렬합니다. [2, 3, 5, 6]의 세 번째 숫자는 5입니다.
[1, 5, 2, 6, 3, 7, 4]를 4번째부터 4번째까지 자른 후 정렬합니다. [6]의 첫 번째 숫자는 6입니다.
[1, 5, 2, 6, 3, 7, 4]를 1번째부터 7번째까지 자릅니다. [1, 2, 3, 4, 5, 6, 7]의 세 번째 숫자는 3입니다.
Sol1) 이중 반복문
#include <algorithm> #include <vector> 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> split; for(int j=commands[i][0]; j<=commands[i][1]; j++){ split.push_back(array[j-1]); } sort(split.begin(), split.end()); answer.push_back(split[commands[i][2]-1]); split.clear(); } return answer; }
Sol2) 단일 반복문
#include <algorithm> #include <vector> using namespace std; vector<int> solution(vector<int> array, vector<vector<int>> commands) { vector<int> answer; vector<int> temp; for(int i=0; i<commands.size(); i++){ temp = array; sort(temp.begin() + commands[i][0] -1, temp.begin() + commands[i][1]); answer.push_back(temp[commands[i][0] + commands[i][2] - 2]); } return answer; }
* vector의 특정 부분만 정렬할 수 있다.
sort(temp.begin() + commands[i][0] -1, temp.begin() + commands[i][1]);
'Study > Coding Test' 카테고리의 다른 글
[정렬] H-Index (0) 2021.02.02 [정렬] 가장 큰 수 (0) 2021.02.02 [힙] 더 맵게 (0) 2021.01.31 [스택/큐] 프린터 (0) 2021.01.31 [스택/큐] 다리를 지나는 트럭 (0) 2021.01.30