728x90
문제 설명
정수 배열 num_list와 정수 n이 매개변수로 주어집니다. num_list를 다음 설명과 같이 2차원 배열로 바꿔 return하도록 solution 함수를 완성해주세요.
num_list가 [1, 2, 3, 4, 5, 6, 7, 8] 로 길이가 8이고 n이 2이므로 num_list를 2 * 4 배열로 다음과 같이 변경합니다. 2차원으로 바꿀 때에는 num_list의 원소들을 앞에서부터 n개씩 나눠 2차원 배열로 변경합니다.
num_list | n | result |
[1, 2, 3, 4, 5, 6, 7, 8] | 2 | [[1, 2], [3, 4], [5, 6], [7, 8]] |
제한사항
- num_list의 길이는 n의 배 수개입니다.
- 0 ≤ num_list의 길이 ≤ 150
- 2 ≤ n < num_list의 길이
입출력 예
num_list | n | result |
[1, 2, 3, 4, 5, 6, 7, 8] | 2 | [[1, 2], [3, 4], [5, 6], [7, 8]] |
[100, 95, 2, 4, 5, 6, 18, 33, 948] | 3 | [[100, 95, 2], [4, 5, 6], [18, 33, 948]] |
입출력 예 설명
입출력 예 #1
- num_list가 [1, 2, 3, 4, 5, 6, 7, 8] 로 길이가 8이고 n이 2이므로 2 * 4 배열로 변경한 [[1, 2], [3, 4], [5, 6], [7, 8]] 을 return합니다.
입출력 예 #2
- num_list가 [100, 95, 2, 4, 5, 6, 18, 33, 948] 로 길이가 9이고 n이 3이므로 3 * 3 배열로 변경한 [[100, 95, 2], [4, 5, 6], [18, 33, 948]] 을 return합니다.
1
2
3
4
5
6
7
8
9
10
11
12
|
class Solution {
public int[][] solution(int[] num_list, int n) {
int[][] answer = new int[num_list.length/n][n];
int index = 0;
for(int i=0;i<answer.length;i++) {
for(int j=0;j<answer[i].length;j++) {
answer[i][j] = num_list[index++];
}
}
return answer;
}
}
|
행의 수를 배열길이/n으로 하고 열의 수를 n으로 하는 2차원 배열을 만든다. 2차원 배열을 행/열 순서로 반복하면 index값을 1씩 증가 시키며 2차원 배열에 복사한다. |
1
2
3
4
5
6
7
8
9
10
11
12
|
class Solution {
public int[][] solution(int[] num_list, int n) {
int[][] answer = new int[num_list.length / n][n];
int index = 0;
for (int i = 0; i < num_list.length; i += n) {
// int[] newArray = Arrays.copyOfRange(num_list, i, i + n);
// answer[index++] = newArray;
System.arraycopy(num_list, i, answer[index++], 0, n);
}
return answer;
}
}
|
자바에서 배열명은 참조형 변수이고 동적배열이이다. System.arraycopy(원본배열, 원본 시작위치, 사본배열, 사본 시작위치, 개수) 이므로 System.arraycopy(num_list, i, answer[index++], 0, n); 이렇게 하면 n개씩 다음줄에 복사가 된다. Arrays.copyOfRange(원본배열, 어디서부터, 어디전까지) 이므로 이것을 사용해도 된다. |
728x90
'프로그래머스 코딩(자바) > Level 0' 카테고리의 다른 글
Programmers Level 0 - k의 개수 (0) | 2023.03.03 |
---|---|
Programmers Level 0 - 가까운 수 (0) | 2023.03.03 |
Programmers Level 0 - 팩토리얼 (0) | 2023.03.03 |
Programmers Level 0 - A로 B 만들기 (0) | 2023.03.03 |
Programmers Level 0 - 모스부호 (1) (0) | 2023.03.03 |