[프로그래머스] 42748. K번째수
2025. 11. 20. 19:15ㆍCS & Algorithm/문제풀이
https://school.programmers.co.kr/learn/courses/30/lessons/42748?language=java

문제 설명
주어진 배열 array와, 각 [i, j, k]로 이루어진 commands 배열이 있을 때
array의 i번째부터 j번째까지 자르고, 정렬한 뒤, k번째 숫자를 선택하여 결과 배열로 반환
접근 방식
- commands 배열을 하나씩 순회한다
- array에서 i번째 ~ j번째까지 잘라 새로운 배열 생성
int start = commands[i][0] - 1; // 0-based 변환
int end = commands[i][1]; // end는 포함되지 않음
int[] sliced = Arrays.copyOfRange(array, start, end);
3. 잘라낸 배열을 오름차순 정렬
// 오름 차순
Arrays.sort(sliced);
// 내림 차순
Arrays.sort(arr, Collections.reverseOrder());
4. 정렬된 배열에서 k번째 요소 선택
5. 결과 배열(answer)의 i번째 위치에 기록
나의 풀이 코드
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++) {
// 자르기 commands 의 0번째부터 1번째까지
int[] temp = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
// 정렬
Arrays.sort(temp);
// 자리에 해당하는 숫자가져오기
answer[i] = temp[commands[i][2] - 1];
}
return answer;
}
}
리팩토링 코드
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
int start = commands[i][0] - 1; // 0-based 변환
int end = commands[i][1]; // end는 exclusive
int target = commands[i][2] - 1;
int[] sliced = Arrays.copyOfRange(array, start, end);
Arrays.sort(sliced);
answer[i] = sliced[target];
}
return answer;
}
}
'CS & Algorithm > 문제풀이' 카테고리의 다른 글
| [Codility] CyclicRotation (0) | 2025.11.22 |
|---|---|
| [프로그래머스] 68644. 두 개 뽑아서 더하기 (0) | 2025.11.20 |
| [Codility] BinaryGap (0) | 2025.11.20 |
| [Leet Code] 20. Valid Parentheses (0) | 2025.11.20 |
| [백준] 10870. 피보나치수 5 (0) | 2025.10.10 |