반응형
문제
코딩테스트 연습 - K번째수
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
programmers.co.kr
풀이
1. 커맨드 별로 진행한다.
2. 배열의 i번째부터 j번째까지 리스트에 담고 정렬한다. k번째 수를 정답 배열에 추가한다.
3. 로직이 시작될 때, 이전 연산이 남지 않도록 리스트를 비운다.
전체 소스코드
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
List<Integer> list = new ArrayList<>();
for (int i = 0; i < commands.length; i++) {
int[] command = commands[i];
list.clear();
for (int j = command[0]-1; j < command[1]; j++) {
list.add(array[j]);
}
Collections.sort(list);
answer[i] = list.get(command[2]-1);
}
return answer;
}
}
다른 풀이
리스트를 사용하지 않고 내부에 배열 생성해서 배열 카피 후 정렬, 그리고 k번째 수 찾음.
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[] command = commands[i];
int[] parts = Arrays.copyOfRange(array, command[0]-1, command[1]);
Arrays.sort(parts);
answer[i] = parts[command[2]-1];
}
return answer;
}
}
'Algorithm' 카테고리의 다른 글
[Algorithm] 프로그래머스 더 맵게 (0) | 2021.07.04 |
---|---|
[Algorithm] 프로그래머스 H-index (0) | 2021.07.03 |
[Algorithm] 프로그래머스 소수 찾기 (0) | 2021.07.01 |
[Algorithm] 프로그래머스 모의고사 (0) | 2021.06.30 |
[Algorithm] 프로그래머스 카펫 (0) | 2021.06.29 |