알고리즘

Convert 1D Array Into 2D Array

짬뽕얼큰하게 2025. 2. 11. 08:53

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;
    }
};