문제
해결 방안 고민
•
2차원 배열과 Java에 대한 기초개념 그리고 정렬 자료구조를 적절하게 활용하면 풀 수 있는 문제이다.
•
start와 end를 어떻게 정해서 활용할 것인지를 조금만 고민하면 된다.
•
2차원 배열을 어떻게 순회시킬 것인지가 핵심이다.
해결 방법
•
향상된 for 문을 활용하여 2차원 배열의 요소를 순회한다.
•
시작과 끝을 정한다.
◦
start = command[0] - 1
◦
end = command[1] - 1
•
commands 배열의 길이가 1이상 50 이하가 될 수 있기 때문에 answer 배열의 길이를 동적으로 설정해야 하므로 List를 활용하였다.
코드
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
List<Integer> list = new ArrayList<>();
// 배열 순회
for (int[] command : commands) {
int start = command[0] - 1; // 배열은 0부터 시작하므로
int end = command[1] - 1;
int[] temp = new int[end - start + 1];
int idx = 0;
for (int j = start; j <= end; j++) {
temp[idx++] = array[j];
}
Arrays.sort(temp);
list.add(temp[command[2] - 1]);
}
int size = list.size();
int[] answer = new int[size];
for (int i = 0; i < size; i++) {
answer[i] = list.get(i);
}
return answer;
}
}
Java
복사