💡 문제
💬 입출력 예시
📌 풀이(소스코드)
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
List<Integer> answer = new ArrayList<>();
for (int[] command : commands) {
int i = command[0];
int j = command[1];
int k = command[2];
int[] temp = new int[j - i + 1];
int index = 0;
for (int l = i-1; l < j; l++) {
temp[index++] = array[l];
}
Arrays.sort(temp);
answer.add(temp[k-1]);
}
return answer.stream().mapToInt(Integer::intValue).toArray();
}
}
📄 해설
접근
- i 번째 숫자부터, j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 찾는 문제
- 정렬 메소드만 사용할줄 알면 쉽게 해결이 가능하다.
- 인덱스 번호에 유의할 것
과정
commands
배열을 순회하면서 i
, j
, k
를 뽑아내고, 주어진 조건대로, 우선 i
번째 숫자부터 j
번째 숫자까지 임시 배열 temp
에 담는다.
temp
배열을 오름차순으로 정렬한 다음, k
번째 숫자를 찾고, answer
리스트에 추가한다.
answer
리스트를 배열로 변환해서 반환한다.