개발자를 향해...

프로그래머스 - k번째 수 (java) 본문

코테 공부/프로그래머스master

프로그래머스 - k번째 수 (java)

eugeneHwang1124 2022. 4. 8. 01:15
728x90
반응형

https://programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        System.out.println(commands.length);
        for(int i=0; i<commands.length; i++){
            for(int j = 0; j<3; j++){
                int start = commands[i][0];
                int end = commands[i][1];
                
                int[] result = sort(Arrays.copyOfRange(array,start-1,end));
                answer[i] = result[commands[i][2]-1];
                
            }
        }
        return answer;
    }
    
    public static int[] sort(int[] array){
        
        for(int i=1; i<array.length;i++){
            int j=i-1;
            int temp = array[i];
            
            // 이전 원소를 한칸 씩 뒤로 민다.
            while(j>=0 &&(array[j] > temp)){
                array[j+1] =array[j];
                j--;
            }
            
            // 앞의 모든 원소가 타겟보다 작기 때문에 타겟을 j+1에 위치시킨다.
            array[j+1]=temp;
            
            // for(int k=0; k<array.length; k++)
            //     System.out.print(array[k]+" ");
            // System.out.println("");
        }
        return array;
    }
}

 

삽입 sort 를 이용해 풀었다. 

반응형