알고리즘/정렬

프로그래머스 - K번째수(Java)

연향동큰손 2025. 1. 10. 20:42

 

정렬만 라이브러리를 이용해서 구현 한다면 어려운 문제는 아니다.

 

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = {};
        int size = commands.length;
        answer=new int[size];
        for(int i=0; i<size; i++){
            int[] arr = new int[commands[i][1]-commands[i][0]+1];
            int j=0;
            int start =commands[i][0]-1;
            while(start<=commands[i][1]-1){
                arr[j]=array[start];
                j++;
                start++;
            }
            Arrays.sort(arr);
            answer[i]=arr[commands[i][2]-1]; 
        }
        return answer;
    }
}

 

 


 

2025 - 03 - 13 풀이

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        Queue<Integer> queue = new LinkedList<>();
        
        for(int i=0; i<commands.length; i++){
            int x = commands[i][0];
            int y = commands[i][1];
            int z = commands[i][2];
            int size = (y-x)+1;
            int[] arr = new int[size];
            
            int k =0;
            for(int j=x-1; j<=y-1; j++){
                arr[k]=array[j];
                k+=1;
            }
            
            Arrays.sort(arr);
            queue.add(arr[z-1]);
        }
        
        int a = queue.size();
        int[] answer = new int[a];
        
        for(int i=0; i<a; i++){
            answer[i]=queue.poll();
        }
        
        return answer;
    }
}