배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
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입니다.
import java.util.ArrayList;
import java.util.Collections;
class Solution {
public int[] solution(int[] array, int[][] commands) {
ArrayList<Integer> aList = new ArrayList<>(commands.length); // 커맨드 크기만큼의 정답 배열리스트 선언
for(int i = 0; i<commands.length; i++) {
ArrayList<Integer> temp = new ArrayList<>();
for(int j=commands[i][0]-1; j<=commands[i][1]-1; j++) { // 배열 자르기
temp.add(array[j]);
}
Collections.sort(temp); // 자른 배열 정렬
aList.add(temp.get(commands[i][2]-1)); // k번째 수 저장
}
int[] answer = new int[aList.size()]; // 정답 배열 리스트를 정수 배열로 변환
for(int idx=0; idx<aList.size(); idx++) {
answer[idx] = aList.get(idx);
}
return answer;
}
}
어렵지는 않았으나 Arrays.copyOfRange를 몰라 직접 구현했다.