CODING/스파르타 내일배움캠프 TIL
49_K번째수 정렬_25.2.26(수)
codingTrip
2025. 2. 26. 22:57
코드카타
48) K번째수 정렬
나의 풀이
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
List<Integer> answerList = new ArrayList<>();
List<Integer> answerList2 = new ArrayList<>();
for (int i = 0; i < commands.length; i++) {
int start = commands[i][0]-1;
int end = commands[i][1];
int k = commands[i][2]-1;
for (int j = start; j < end; j++) {
answerList.add(array[j]);
answerList2.add(array[j]);
}
Collections.sort(answerList);
answer[i] = answerList.get(k);
answerList.removeAll(answerList2);
}
return answer;
}
}
리스트에 저장해서 계속 내용을 삭제해 주었다.
다른 분들의 풀이
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for(int i=0; i<commands.length; i++){
int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(temp);
answer[i] = temp[commands[i][2]-1];
}
return answer;
}
}
출처 : https://school.programmers.co.kr/learn/courses/30/lessons/42748/solution_groups?language=java
copyOfRange를 사용하셨다...
Arrays에도 sort 기능이 있다는 것을 알게 되었다.