프로그래밍

[Programmers] K번째 수

tedhong 2023. 2. 20. 12:55
2019-07-19 글쓴이 TED HONG

[Programmers] K번째 수

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

JAVA

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

        for(int i = 0; i < cnt; ++i){
            answer[i] = getSelectValue(array, commands[i]);            
        }
        //System.out.println("answer ="+Arrays.toString(answer));
        return answer;
    }

    static int getSelectValue(int[] array, int[] command){
        int start = command[0] - 1 ;
        int end = command[1];
        int index = command[2] - 1;
        //System.out.println(start + " / "+end+ " / "+index);
        int[] temp = Arrays.copyOfRange(array, start, end);
        Arrays.sort(temp);
        //System.out.println("temp ="+Arrays.toString(temp));
        return temp[index];
    }    

 

이렇게 해도 됨
public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for(int i = 0 ; i < commands.length; i++)
        {
            int size = commands[i][1] - (commands[i][0] - 1);
            int[] copyArray = new int[size];
            System.arraycopy(array, commands[i][0] - 1, copyArray, 0, size);
            Arrays.sort(copyArray);
            answer[i] = copyArray[commands[i][2]-1];
        }
        return answer;
    }