public static int[] solution(int[] num_list, int n) {
int j=0;
int[] arr = new int[num_list.length-n+1];
for(int i=n-1; i<num_list.length; i++){
arr[j]=num_list[i];
j++;
}
return arr;
}
먼저 int 배열을 받은 것을 n번째부터 배열 끝까지 출력하기 위해 for문을 사용해서 출력해줬다. 하지만 이 방법보다 더 효율적인 방법이 있다.
바로 System.arraycopy (성능 최적화), Arrays.copyOfRange (가독성 최적화) 이다.
for문 대신 System.arraycopypublic static int[] solution(int[] num_list, int n) {
int length = num_list.length - n + 1;
int[] arr = new int[length];
// 원본배열, 시작위치, 복사본배열, 복사본시작위치, 복사할길이
System.arraycopy(num_list, n - 1, arr, 0, length);
return arr;
}
arr을 설정해주고 arraycopy를 사용해서 기존의 num_list에서 복사해주면 된다.
원본배열, 시작위치, 복사본배열, 복사본시작위치, 복사할길이 순서대로 입력해주면 된다.
Arrays.copyOfRange (가독성 최적화)public static int[] solution(int[] num_list, int n) {
// n-1 인덱스부터 num_list.length 인덱스 "전"까지 복사
return Arrays.copyOfRange(num_list, n - 1, num_list.length);
}
바로 활용할 수 있는 방법으로 n-1 인덱스부터 num_list.length 인덱스 "전"까지 복사한다.
| 구분 | int | ArrayList |
|---|---|---|
| 크기 | 고정 (한번 정하면 못 바꿈) | 가변 (알아서 늘어남) |
| 속도 | 매우 빠름 | 상대적으로 느림 |
| 메모리 | 효율적 (필요한 만큼만) | 비효율적 (여유 공간 필요) |
| 데이터 타입 | int (기본형) | Integer (객체형) |
num_list.length - n + 1이라는 명확한 크기 계산식이 나올 때는 배열(int[])을 쓰는 것이 메모리 효율과 속도 측면에서 더 좋다고 한다
ArrayList는 입력되는 데이터가 몇 개일지 도저히 모를 때, 중간에 데이터를 넣거나 빼야 할 때(배열은 삭제가 힘들지만, ArrayList는 메서드 하나로 해결) 사용하는게 좋다.