👩🏻💻 기술면접/알고리즘
[프로그래머스] JAVA K번째 수 Level 1.
wooaoe
2020. 5. 16. 22:25
💡 나의 풀이
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 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(배열, 시작인덱스, 마지막인덱스)를 사용하여 배열을 slicing 해준다.
시작인덱스는 포함되고, 마지막인덱스는 포함되지 않는다. commands[i][0]에서 -1을 해주는 이유는 인덱스 시작점을 찾기 위해서이다. commands[0][0] = 2, [1][0] = 4, [2][0] = 1이고 2번째부터 시작, 4번째부터 시작, 1번째부터 시작을 하려면 각각 -1을 해줘야 배열의 인덱스 번호로 찾아갈 수 있다.
answer[i] = temp[commands[i][2]-1]도 마찬가지이다.