[Programmers] #42748 - K번째수 [Java][C++][Python]
[Programmers] #42748 - K번째수 [Java][C++][Python]
1. 아이디어
명령 $[i, j, k]$마다 배열의 $i$번째부터 $j$번째까지를 잘라 정렬하고 $k$번째 수를 고르면 되는 문제이다. 지문은 위치를 1부터 세므로 0부터 세는 반열린 구간으로는 $[i - 1, j)$이고 $k$번째 수는 인덱스 $k - 1$에 있다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
List<Integer> ans = new ArrayList<>();
for (int[] c : commands) {
int i = c[0], j = c[1], k = c[2];
int[] tmp = Arrays.copyOfRange(array, i - 1, j);
Arrays.sort(tmp);
ans.add(tmp[k - 1]);
}
return ans.stream().mapToInt(Integer::intValue).toArray();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> ans;
for (auto& c : commands) {
int i = c[0], j = c[1], k = c[2];
vector<int> tmp(array.begin() + i - 1, array.begin() + j);
sort(tmp.begin(), tmp.end());
ans.push_back(tmp[k - 1]);
}
return ans;
}
1
2
3
4
5
6
7
def solution(array, commands):
ans = []
for i, j, k in commands:
tmp = sorted(array[i - 1 : j])
ans.append(tmp[k - 1])
return ans
This post is licensed under CC BY 4.0 by the author.