[Algo/Programmers] 자바 - K번째수
6312 단어 JavaprogrammersalgorithmJava
[Algorithm/Programmers] 자바 - K번째수
문제 | 플랫폼 | 난이도 | 유형 | 풀이 링크 | 문제 링크 |
---|---|---|---|---|---|
K번째수 | Programmers | Level 1 | Sort | 풀이 | 문제 |
풀이
문제를 해결하기 위한 순서는 다음과 같습니다.
1. 주어진 배열 array
의 i번째 숫자부터 j번재 숫자까지
자르고,
2. 정렬한 뒤,
3. k번째 있는 수를 구합니다.
해당 순서는 commands
2차원 배열의 길이만큼 명령을 반복하면 됩니다.
public int[] solution(int[] array, int[][] commands) {
int len = commands.length;
int[] ans = new int[len];
// command 수만큼 반복합니다.
for (int i = 0; i < len; i++) {
// slicing한 값을 넣어둘 임시 배열을 생성합니다.
int[] temp = new int[commands[i][1] - commands[i][0] + 1];
int idx = 0;
// 1. 주어진 command대로 slicing합니다.
for (int j = commands[i][0] - 1; j < commands[i][1]; j++) {
temp[idx++] = array[j];
}
// 2. Slicing한 배열을 정렬합니다.
Arrays.sort(temp);
// 3. 해당 command 턴의 답(k번째수)를 ans배열에 넣습니다.
ans[i] = temp[commands[i][2] - 1];
}
return ans;
}
문제는 배열을 이용하여 간단하게 풀었습니다.
주어진 순서에만 유의하며 풀면 간단한 문제입니다.
Author And Source
이 문제에 관하여([Algo/Programmers] 자바 - K번째수), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@rgunny/AlgoProgrammers-자바-K번째수저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)