Post

[Programmers] #120842 - 2차원으로 만들기 [Java][C++][Python]

[Programmers] #120842 - 2차원으로 만들기 [Java][C++][Python]

문제 링크


1. 아이디어

num_list의 길이가 n의 배수이므로, 앞에서부터 n개씩 잘라 행으로 쌓으면 빈 자리 없이 맞아떨어진다. 행의 개수는 num_list의 길이를 n으로 나눈 값이고, 각 행에는 원본을 앞에서부터 훑으며 다음 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 < 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;
}
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.