정렬 - K번째 수

coding by 스플릿·2021년 12월 19일

스터디

목록 보기
1/11

https://programmers.co.kr/learn/courses/30/parts/12198

python3

문제

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

입력값

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

코드 ( PYTHON3 )

def solution(array, commands):
    ret = list()
    for l in range(len(commands)):
        command = commands[l]
        i,j,k = command
        chopped = array[i-1:j]
        chopped.sort()
        ret.append(chopped[k-1])
    return ret

코드 ( JAVA )

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

0개의 댓글