
프로그래머스 Level 1
🔒 K번째수
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
array의 길이는 1 이상 100 이하입니다.
array의 각 원소는 1 이상 100 이하입니다.
commands의 길이는 1 이상 50 이하입니다.
commands의 각 원소는 길이가 3입니다.
| array | commands | return |
|---|---|---|
| [1, 5, 2, 6, 3, 7, 4] | [[2, 5, 3], [4, 4, 1], [1, 7, 3]] | [5, 6, 3] |
[1, 5, 2, 6, 3, 7, 4]를 2번째부터 5번째까지 자른 후 정렬합니다. [2, 3, 5, 6]의 세 번째 숫자는 5입니다.
[1, 5, 2, 6, 3, 7, 4]를 4번째부터 4번째까지 자른 후 정렬합니다. [6]의 첫 번째 숫자는 6입니다.
[1, 5, 2, 6, 3, 7, 4]를 1번째부터 7번째까지 자릅니다. [1, 2, 3, 4, 5, 6, 7]의 세 번째 숫자는 3입니다.
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for(int n=0; n<commands.length; n++) {
int i = commands[n][0];
int j = commands[n][1];
int k = commands[n][2];
int[] answ = new int[j-i+1];
for(int m=0; m<(j-i+1); m++) {
answ[m] = array[m+i-1];
}
Arrays.sort(answ);
answer[n] = answ[k-1];
}
return answer;
}
}
i, j, k가 commands의 행만큼 제공된다는 것이므로 answer를 commands의 행과 같은 크기로 선언하고 시작했다.
commands의 행을 돌면서 각각 i, j, k를 선언해주고 i부터 j만큼 자를 배열 answ도 선언해준다.
Arrays.sort()로 자른 배열을 정렬해주고 k번째에 있는 요소를 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[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(temp);
answer[i] = temp[commands[i][2]-1];
}
return answer;
}
}
Arrays.copyOfRange()라는 게 있었구나...
배열의 특정 범위를 복사하는 메소드라고 한다.