[프로그래머스] 정렬 - K번째수 (Level 1)

K번째수


Python Code

def solution(array, commands):
    answer = []
    for i in commands:
        temp = array[i[0]-1:i[1]]
        temp.sort()
        answer.append(temp[i[2]-1])
    return answer

Java Code

import java.util.Arrays;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        //풀이1 - 라이브러리 사용
        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];
        }
        
        
        //풀이2 - 라이브러리 사용 X
        for(int i=0; i<commands.length; i++){
            //배열 자르기
            int[] temp = new int[commands[i][1]-commands[i][0]+1];
            int count = 0;
            for(int j=0; j<array.length; j++){
                if(j>=commands[i][0]-1 && j<=commands[i][1]-1){
                    temp[count++] = array[j];
                }
            }
            //선택 정렬
            for(int a=0; a<temp.length-1; a++){
                int min = a;
                for(int b=a+1; b<temp.length; b++){
                    if(temp[b]<temp[min]){
                        min = b;
                    }
                }
                int temp2 = temp[a];
                temp[a] = temp[min];
                temp[min] = temp2;
            }
            
            
            answer[i] = temp[commands[i][2]-1];
        }
        
        
        return answer;
    }
}

좋은 웹페이지 즐겨찾기