✔ K번째수
문제 분석하기
배열을 복사한 후 정렬하여 i번째 숫자와 j번째 사이에 있는 k번째 수를 구하도록 함
손으로 풀어보기
- 배열의 i번째 숫자부터 j번째 숫자까지를 복사
- 복사한 배열을 정렬한 후 k번째 수를 정답 배열에 저장
- 정답 배열 리턴
슈도코드 작성하기
array(숫자 배열)
commands(i, j, k가 담긴 배열)
answer(정답 배열)
for(commands만큼) {
temp(임시 배열) = Arrays.copyOfRange(array, 복사 시작 인덱스, 복사 끝 인덱스)
temp 정렬
정답 배열에 저장
}
정답 배열 반환
코드 구현하기
/**
* 42748) K번째수
*/
public class K001_42748 {
// array(숫자 배열)
// commands(i, j, k가 담긴 배열)
public int[] solution(int[] array, int[][] commands) {
// answer(정답 배열)
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
// temp(임시 배열) = Arrays.copyOfRange(array, 복사 시작 인덱스, 복사 끝 인덱스)
int[] temp = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
// temp 정렬
Arrays.sort(temp);
// 정답 배열에 저장
answer[i] = temp[commands[i][2] - 1];
}
// 정답 배열 반환
return answer;
}
// 테스트 케이스
public static void main(String[] args) {
K001_42748 solution = new K001_42748();
int[] array = { 1, 5, 2, 6, 3, 7, 4 };
int[][] commands = { { 2, 5, 3 }, { 4, 4, 1 }, { 1, 7, 3 } };
int[] result = solution.solution(array, commands);
System.out.println(Arrays.toString(result));
}
}
'Coding Test > Java 알고리즘 실전' 카테고리의 다른 글
[42862] 체육복 (0) | 2023.10.30 |
---|---|
[86491] 최소직사각형 (0) | 2023.10.29 |
[42626] 더 맵게 (0) | 2023.10.28 |
[12906] 같은 숫자는 싫어 (0) | 2023.10.28 |
[1845] 폰켓몬 (0) | 2023.10.27 |