프로그래머스 스쿨 'K번째 수' 를 풀이 중 자바 메서드인 copyOfRange 라는 것을 처음 보게 되어 작성하였습니다.
사용 방법은
int[] array = {1,2,3,4,5};
int[] arr = Arrays.copyOfRange(array,0,2);
매개변수로는 [ Arrays.copyOfRange(복사하고자하는 배열, 시작 위치, 배열크기); ]로 선언해주면 되며, 복사되는 배열은 시작 위치부터 배열크기 바로 전까지 복사된다는 점을 주의하여야 합니다. 위의 코드처럼 배열을 복사해주면 실제 복사되는 배열 arr 에는 정수 1, 2 이 복사된다. 즉, array의 0 ~ 2 인덱스의 값이 저장됩니다.
// 처음 정답 코드
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 n = commands[i][1] - commands[i][0] + 1;
int[] s = new int[n];
for(int j=0;j<n;j++){
s[j] = array[commands[i][0]-1+j];
}
Arrays.sort(s);
answer[i] = s[commands[i][2]-1];
}
return answer;
}
}
// copyOfRange를 알고난 후 사용 코드
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[] s = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(s);
answer[i] = s[commands[i][2]-1];
}
return answer;
}
}
프로그래머스는 다른 사람의 코드를 보며 많이 알아갈 수 있다는 장점이 큰 것 같습니다 ^_^!!