[Programmers] #120842 - 2차원으로 만들기 [Java][C++][Python]
[Programmers] #120842 - 2차원으로 만들기 [Java][C++][Python]
1. 아이디어
배열을 앞에서부터 $n$개씩 끊어 한 행으로 삼은 2차원 배열로 바꾸는 문제다. 배열의 길이가 $n$의 배수이므로 마지막 행까지 정확히 $n$개씩 차고, 시작 인덱스를 $n$씩 늘려 가며(0, $n$, $2n$, …) 각 시작 인덱스부터 $n$개를 한 행으로 잘라 내면 된다.
2. 코드
풀이 [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 < arr.length; 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;
for (int i = 0; i < num_list.size(); i += n) {
v.emplace_back(num_list.begin() + i, num_list.begin() + i + n);
}
return v;
}
emplace_back에 이터레이터 구간을 넘겨 그 구간으로 std::vector<int> 행을 추가했다.
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.