2022 - Convert 1D Array Into 2D Array

 C++

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

JAVA

  • class Solution {
        public int[][] construct2DArray(int[] original, int m, int n) {
            if (m * n != original.length) {
                return new int[0][0];
            }
            int[][] ans = new int[m][n];
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    ans[i][j] = original[i * n + j];
                }
            }
            return ans;
        }
    }

Comments