본문 바로가기

CodingTest Practice

[프로그래머스] K번째수

K번째 수 - 정렬

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

배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어진다. 

commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 반환

 

■ 문제 풀이

[특정 인덱스에서 배열 자르기]
1) 반복문 이용
2) Arrays 클래스의 copyOfRange() 이용
- int[] copyOfRange(int[] original, int from, int to)
- original : 복사 대상 배열
- from : 시작 위치
- to : 복사 범위의 마지막 인덱스, 포함되지는 X

 

import java.util.Arrays;

public class KthNumber {

    static int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];

        for (int i = 0; i < commands.length; i++) {
            int start = commands[i][0]-1;
            int end = commands[i][1];
            int pick = commands[i][2]-1;

            int[] copy = Arrays.copyOfRange(array, start, end);
            Arrays.sort(copy);
            answer[i] = copy[pick];
        }

        return answer;
    }

    public static void main(String[] args) {
        
        int[] array = {1, 5, 2, 6, 3, 7, 4};
        int[][] commands = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};

        solution(array, commands);
    }
}