카테고리 없음

[프로그래머스] K번째수 (Java, Python)

garamdev 2026. 9. 5.
728x90

문제

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

코드(Java)

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        for (int idx = 0; idx < commands.length; idx++) {
            int i = commands[idx][0];
            int j = commands[idx][1];
            int k = commands[idx][2];
            
            // 배열 잘라내기
            int[] sliced = Arrays.copyOfRange(array, i-1, j);
            // 정렬
            Arrays.sort(sliced);
            // k번째 값 저장
            answer[idx] = sliced[k-1];
        }
        
        return answer;
    }
}
  • `Arrays.copyOfRange(array, i-1, j)` → 배열을 i번째부터 j번째까지 잘라냄
  • `Arrays.sort(sliced)` → 잘라낸 배열을 정렬
  • `sliced[k-1]` → 정렬된 배열에서 k번째 값
  • `answer[idx]` → 결과 배열에 저장

👉 자바에서는 리스트보다 배열을 다루는 게 기본

 

코드(Python)

def solution(array, commands):
    answer = []
    for i, j, k in commands:
        # 슬라이싱과 정렬을 한 줄로 처리
        answer.append(sorted(array[i-1:j])[k-1])
    return answer
  • `array[i-1:j]` → 리스트에서 i번째부터 j번째까지 잘라냄
  • `sorted(...)` → 잘라낸 리스트를 정렬
  • `[k-1]` → 정렬된 리스트에서 k번째 숫자
  • `append(...)`  → 결과 리스트에 추가