본문 바로가기
알고리즘

알고리즘 - 프로그래머스 K번째수

by Hyeongjun_Ham 2022. 7. 8.

문제 :

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

입출력 예

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

입출력 예 설명

[1, 5, 2, 6, 3, 7, 4]를 2번째부터 5번째까지 자른 후 정렬합니다. [2, 3, 5, 6]의 세 번째 숫자는 5입니다.
[1, 5, 2, 6, 3, 7, 4]를 4번째부터 4번째까지 자른 후 정렬합니다. [6]의 첫 번째 숫자는 6입니다.
[1, 5, 2, 6, 3, 7, 4]를 1번째부터 7번째까지 자릅니다. [1, 2, 3, 4, 5, 6, 7]의 세 번째 숫자는 3입니다.

 

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for(int i =0; i<commands.length; i++){
            int a = commands[i][0];
            int b = commands[i][1];
            int[] c= Arrays.copyOfRange(array, a-1,b);
            Arrays.sort(c);
            int result = c[commands[i][2]-1];
            answer[i] = result;
        }
        return answer;
    }
}

 

Arrays.CopyOfRange(원본 배열, 복사할 시작 인덱스, 복사할 끝 인덱스) : 배열 복사

Arrays.sort(배열) : 오름차순 정렬