02-07 11:18
Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
관리 메뉴

기록을 합시다.

[프로그래머스] k번째 수(python/java) 본문

공부/알고리즘

[프로그래머스] k번째 수(python/java)

울집고양이세마리 2023. 6. 5. 18:06

문제 요약

commands변수에 담긴 명령들을 이용해서 배열을 부분 정렬하고, 부분 정렬한 곳에서 특정 인덱스의 값들을 반환하라.

파이썬으로 제출한 정답

def solution(array, commands):
    answer = []
    for command in commands:
        a, b, idx = command 
        new_list = sorted(array[a-1:b])
        answer.append(new_list[idx-1])

    return answer

자바로 제출한 정답

import java.util.*;

class Solution {
    public List<Integer> solution(int[] array, int[][] commands) {
        List<Integer> answer = new ArrayList<Integer>();

        for(int[] command : commands){
            int i = command[0];
            int j = command[1];
            int k = command[2];

            int[] subArray = Arrays.copyOfRange(array, i-1, j);
            Arrays.sort(subArray);

            answer.add(subArray[k-1]);
        }
        return answer;
    }
}

해설

내가 생각한 로직은 다음과 같다.

  • commands 안에 들어있는 명령들을 하나씩 꺼낸다.
  • 명령에 따라 array를 슬라이스 하고, sort한 후에 특정 인덱스 값을 가져온다.

이것도 코드는 쉬워서 코드 설명은 제외!!

Comments