넘치게 채우기

[LeetCode] 2022. Convert 1D Array Into 2D Array 본문

PS/LeetCode

[LeetCode] 2022. Convert 1D Array Into 2D Array

riveroverflow 2024. 9. 1. 10:20
728x90
반응형

https://leetcode.com/problems/convert-1d-array-into-2d-array/description/?envType=daily-question&envId=2024-09-01

leetcode - Convert 1D Array Into 2D Array

문제 유형 : 행렬, 배열, 구현

문제 난이도 : Easy

 

문제

You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with  m rows and n columns using all the elements from original.

The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.

Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.

 

1차원배열 original과 두 정수 m, n이 주어진다.

original을 m * n의 2차원배열로 변환하시오.

단, 만들 수 없으면 빈 배열을 반환하시오.

 

풀이

m x n짜리 2D배열을 만든다.

arr[i][j]의 값은 original[i * n + j]의 값을 넣어주면 된다.

배열을 본질적으로 생각해보자.

 

코드

C++

#pragma GCC optimize("03", "unroll-loops");
static const int __ = [](){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    return 0;
}();

class Solution {
public:
    vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
        vector<vector<int>> ans(m, vector<int>(n));
        if(m * n != original.size()) return {};
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                ans[i][j] = original[n * i + j];
            }
        }

        return ans;
    }
};

 

GO

func construct2DArray(original []int, m int, n int) [][]int {
    if len(original) != m*n {
        return nil
    }

    ans := make([][]int, m)
    for i := 0; i < m; i++ {
        ans[i] = make([]int, n)
        for j := 0; j < n; j++ {
            ans[i][j] = original[i*n+j]
        }
    }

    return ans
}
728x90
반응형