코딩테스트/Programmers

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

grove1212 2025. 2. 28. 16:15

1. 내 풀이

System.arraycopy 사용

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        int[] list;
        
        for(int i = 0; i < commands.length ; i++) {
            list = new int[commands[i][1] - commands[i][0] + 1];
            System.arraycopy(array, commands[i][0] - 1, list, 0, commands[i][1] - commands[i][0] + 1);
            Arrays.sort(list);
            answer[i] = list[commands[i][2] - 1];
        }
        return answer;
    }
}

 

2. 다른 분 풀이

Arrays.copyOfRange 사용.

import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];

        for(int i=0; i<commands.length; i++){
            int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(temp);
            answer[i] = temp[commands[i][2]-1];
        }

        return answer;
    }
}