[프로그래머스/Java] K번째 수

Yujin·2025년 6월 18일

CodingTest

목록 보기
11/51

문제

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

문제풀이 방법

뽑아온 배열을 저장할 result라는 배열 생성
반복문을 사용해서 result 배열에 해당되는 array배열의 값을 저장 -> 정렬
answer의 배열에 result의 K-1을 저장 -> K-1을 하는 이유 3번째 숫자면 result[2]의 값이기때문

나의 코드

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int [commands.length];
        
        for(int i = 0; i < commands.length; i++){
            int start = commands[i][0];
            int end = commands[i][1];
            int K = commands[i][2];
            int[] result = new int[end - start + 1]; 
            
            int index = 0; 
            for(int j = start - 1; j < end; j++){
                result[index++] = array[j];
            }
            
            Arrays.sort(result);
            answer[i] = result[K - 1];
        }
        return answer;
    }
}

0개의 댓글