[ K번째 수 ]
https://programmers.co.kr/learn/courses/30/lessons/42748
- 배열 값을 받을 ArrayList를 하나, commands값을 담을 ArrayList도 만들고 정답에 담아줄 List값을 하나 만들어준다.
- 찾을 숫자의 갯수(commands의 길이)만큼 반복하고 숫자를 찾을 때 마다 clear후 재입력하여 입력 받은 배열을 리스트에 담아준다.
clear하는 이유는 아래 Collections.sort를 하면 ar값도 정렬되기 때문에 clear해서 다시 담아두는중- ijk 리스트에 i부터 j번째까지 k번째 수를 찾을 commands값을 담아준다
- 입력 받은 배열(ar)을 Collections.sort()로 정렬한 후 subList(formIndex, toIndex)를 통해서 i부터 j까지 잘라 list에 저장
- list를 answer에 .get()함수로 요소를 저장 후 이를 commands의 길이(찾을 갯수) 만큼 반복 후 answer을 리턴한다
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
ArrayList<Integer> ar = new ArrayList<Integer>(); // array
ArrayList<Integer> ijk = new ArrayList<Integer>(); // commands
List<Integer> list = new ArrayList<Integer>();
for (int a = 0; a < commands.length; a++) { // commands(찾을) 횟수만큼 반복
ar.clear();
for (int arr : array) {
ar.add(arr);
}
ijk.clear();
for (int b = 0; b < 3; b++) { // 구간 지정
ijk.add(commands[a][b]);
}
list = ar.subList(ijk.get(0) - 1, ijk.get(1)); // 구간만큼 자르기
Collections.sort(list); // 자른 구간 정렬
answer[a] = list.get(ijk.get(2) - 1); // 자른 구간에서 commands[n][2]를 정답에 추가
}
return answer;
}
}
.clear()란? 리스트를 빈칸으로 정리해주는 함수
.Collections.sort()란? Array.sort()는 배열을 정렬해주는 것이면, Collections.sort()는 List 객체를 정렬해주는
.subList(fromindex, toindex)란? 리스트의 fromindex(포함)부터 toindex까지 잘라주는 메서드로 index는 1부터 시작한다