알고리즘 & 자료구조/정렬
[프로그래머스 알고리즘 고득점 Kit][정렬][Java] K번째 수
수수다
2026. 2. 16. 20:25
https://school.programmers.co.kr/learn/courses/30/lessons/42748
정답 코드
유의점 i, j, k는 1~n을 따라서
배열의 인덱스를 0~n-1인지 잘 체크해줘야한다.
Integer.compare를 쓰는 이유
여기선 필요없는데 (정수 - 정수)가 Integer의 범위를 넘겨 오버플로우가 나는 것을 예방하기 위해
사용한다.
import java.io.*;
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int m = commands.length;
int[] answer = new int[m];
for(int c=0; c<m; c++){
ArrayList<Integer> newArr = new ArrayList<>();
int i = commands[c][0]-1;
int j = commands[c][1]-1;
int k = commands[c][2]-1;
for(int l=i; l<=j; l++){
newArr.add(array[l]);
}
newArr.sort((n1, n2) -> {
return Integer.compare(n1, n2);
});
answer[c] = newArr.get(k);
}
return answer;
}
}
