/ PRACTICE

Practice - K번째 수

programmers 바로가기

문제

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.

입출력 예

array commands return
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

풀이

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for(int i = 0; i < commands.length; i++){
            int[] tmp = new int[commands[i][1]-commands[i][0]+1];
            for(int k = 0; k < commands[i][1]-commands[i][0]+1; k++){
                 tmp[k] = array[commands[i][0]+k-1];
            }
            Arrays.sort(tmp);
            answer[i] = tmp[commands[i][2]-1];
        }
        return answer;
    }
}

개선점

Arrays 메소드 중에 copyOfRange라는 좋은게 있었다

int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);