Skip to content

2022. Convert 1D Array Into 2D Array 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
    if (original.size() != m * n)
      return {};

    vector<vector<int>> ans(m, vector<int>(n));

    for (int i = 0; i < original.size(); ++i)
      ans[i / n][i % n] = original[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int[][] construct2DArray(int[] original, int m, int n) {
    if (original.length != m * n)
      return new int[][] {};

    int[][] ans = new int[m][n];

    for (int i = 0; i < original.length; ++i)
      ans[i / n][i % n] = original[i];

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def construct2DArray(self, original: list[int],
                       m: int, n: int) -> list[list[int]]:
    if len(original) != m * n:
      return []

    ans = [[0] * n for _ in range(m)]

    for i, num in enumerate(original):
      ans[i // n][i % n] = num

    return ans