짬뽕얼큰하게의 맨땅에 헤딩 :: Convert 1D Array Into 2D Array

Leetcode Problem:

Summary

  • Construct a 2D array from a 1D array based on given row and column counts.

Approach

  • The approach used is to create a 2D array and then fill it with elements from the 1D array based on the given row and column counts.

Complexity

  • O(m*n)

Explain

  • The solution code first checks if the total number of elements in the 1D array matches the product of the row and column counts
  • If not, it returns an empty 2D array
  • Otherwise, it creates a 2D array with the given row count and then fills it with elements from the 1D array based on the given column count
  • The outer loop iterates over each row, and the inner loop iterates over each column, assigning the corresponding element from the 1D array to the 2D array.

Solution Code:


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

'알고리즘' 카테고리의 다른 글

Sum of Digits of String After Convert  (0) 2025.02.11
Find the Student that Will Replace the Chalk  (0) 2025.02.11
Path with Maximum Probability  (0) 2025.02.11
Most Stones Removed with Same Row or Column  (0) 2025.02.11
Count Sub Islands  (0) 2025.02.11
블로그 이미지

짬뽕얼큰하게

,