[Algo/Programmers] 자바 - K번째수

[Algorithm/Programmers] 자바 - K번째수

문제플랫폼난이도유형풀이 링크문제 링크
K번째수ProgrammersLevel 1Sort풀이문제

풀이

문제를 해결하기 위한 순서는 다음과 같습니다.
1. 주어진 배열 arrayi번째 숫자부터 j번재 숫자까지 자르고,
2. 정렬한 뒤,
3. k번째 있는 수를 구합니다.

해당 순서는 commands 2차원 배열의 길이만큼 명령을 반복하면 됩니다.

public int[] solution(int[] array, int[][] commands) {
    int len = commands.length;

    int[] ans = new int[len];
    // command 수만큼 반복합니다.
    for (int i = 0; i < len; i++) {
        // slicing한 값을 넣어둘 임시 배열을 생성합니다.
        int[] temp = new int[commands[i][1] - commands[i][0] + 1];
        int idx = 0;

        // 1. 주어진 command대로 slicing합니다.
        for (int j = commands[i][0] - 1; j < commands[i][1]; j++) {
            temp[idx++] = array[j];
        }

        // 2. Slicing한 배열을 정렬합니다.
        Arrays.sort(temp);

        // 3. 해당 command 턴의 답(k번째수)를 ans배열에 넣습니다.
        ans[i] = temp[commands[i][2] - 1];

    }
    return ans;
}

문제는 배열을 이용하여 간단하게 풀었습니다.
주어진 순서에만 유의하며 풀면 간단한 문제입니다.

좋은 웹페이지 즐겨찾기