[Programmers] #120842 - 2차원으로 만들기 [Java][C++][Python]
정수 배열을 앞에서부터 n개씩 끊어 2차원 배열로 만드는 워밍업 문제.
[Programmers] #120842 - 2차원으로 만들기 [Java][C++][Python]
1. 아이디어
num_list의 길이가 n의 배수이므로, 앞에서부터 n개씩 잘라 행으로 쌓으면 빈 자리 없이 맞아떨어진다.
행의 개수는 num_list의 길이를 n으로 나눈 값이고, i번째 행은 원본의 i * n부터 (i + 1) * n 직전까지를 그대로 옮긴 것이다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = num_list의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
class Solution {
public int[][] solution(int[] num_list, int n) {
int[][] arr = new int[num_list.length / n][n];
for (int i = 0; i < num_list.length / n; i++) {
System.arraycopy(num_list, i * n, arr[i], 0, n);
}
return arr;
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> solution(vector<int> num_list, int n) {
vector<vector<int>> v(num_list.size() / n, vector<int>(n));
for (int i = 0; i < num_list.size() / n; i++) {
copy(num_list.begin() + i * n, num_list.begin() + (i + 1) * n, v[i].begin());
}
return v;
}
1
2
def solution(num_list, n):
return [num_list[i : i + n] for i in range(0, len(num_list), n)]
This post is licensed under CC BY 4.0 by the author.