본문 바로가기
알고리즘/정렬

[프로그래머스 연습문제 level_2 ] k번째 수

by happyhelen 2024. 1. 19.

 

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        int[] tmpArr = {};
        
        for(int i=0; i<commands.length; i++){
            int startIdx = commands[i][0];
            int endIdx = commands[i][1];
            int xth = commands[i][2];
            
            int idx = 0;
            tmpArr = new int[endIdx-startIdx+1];
            for(int j=startIdx-1; j<endIdx; j++){
                
                tmpArr[idx] = array[j];
                idx++;
            }
            
            Arrays.sort(tmpArr);
            answer[i] = tmpArr[xth-1];
        }
        
        return answer;
    }
}

 

처음에는 위처럼 구현했는데 알고보니 편리한 Array 메소드가 있어서 간단하게 구현할 수 있었다

Arrays. copyOfRange(arr, startIdx, endIdx);

 

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        int[] tmpArr = {};
        
        for(int i=0; i<commands.length; i++){
//             int startIdx = commands[i][0];
//             int endIdx = commands[i][1];
//             int xth = commands[i][2];
            
//             int idx = 0;
//             tmpArr = new int[endIdx-startIdx+1];
//             for(int j=startIdx-1; j<endIdx; j++){
                
//                 tmpArr[idx] = array[j];
//                 idx++;
//             }
            
            tmpArr = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            
            Arrays.sort(tmpArr);
            answer[i] = tmpArr[commands[i][2]-1];
        }
        
        return answer;
    }
}