기록을 합시다.
[프로그래머스] k번째 수(python/java) 본문
문제 요약
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한 후에 특정 인덱스 값을 가져온다.
이것도 코드는 쉬워서 코드 설명은 제외!!
'공부 > 알고리즘' 카테고리의 다른 글
[프로그래머스] 완주하지 못 한 선수 (0) | 2023.06.11 |
---|---|
[프로그래머스] 최소 직사각형(python/java) (0) | 2023.06.11 |
[프로그래머스] 같은 숫자는 싫어(python/java) (0) | 2023.06.05 |
[프로그래머스] 폰켓몬(python/java) (0) | 2023.06.05 |
[프로그래머스] Jaden Case (0) | 2023.04.07 |
Comments