K번째 수

LeeJaeHoon·2022년 3월 9일
0
post-thumbnail

https://programmers.co.kr/learn/courses/30/lessons/42748

commands는 2차원 배열이지만 이문제에서는 굳이 두번돌 필요는 없습니다.

commands를 for문으로 돌면서 i마다 array를 commands[i][0] - 1 부터 commands[i][1]까지 slice해준 후

자른 배열의 commands[i][2] -1 번째를 answer[i]번째에 넣어주면 됩니다.

배열을 자를때 Arrays의 copyOfRange을 이용하여 특정 배열의 원하는 범위만큼 복사하여 새로운 배열을 만들 수 있습니다.

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for (int i = 0; i < commands.length; i++) {
            int[] sliceArray =
               slice(array,commands[i][0] - 1,commands[i][1]); 
            Arrays.sort(sliceArray);
            answer[i] = sliceArray[commands[i][2] - 1];
        }
        return answer;
    }
    public static int[] slice(int[] array, int startIndex, int endIndex) {   
        int[] slicedArray = Arrays.copyOfRange(array, startIndex, endIndex);   
        return slicedArray;   
    }   
}

0개의 댓글