Skip to content

566. Reshape the Matrix 👍

  • Time: $O(rc)$
  • Space: $O(rc)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
    if (nums.empty() || r * c != nums.size() * nums[0].size())
      return nums;

    vector<vector<int>> ans(r, vector<int>(c));
    int k = 0;

    for (const vector<int>& row : nums)
      for (const int num : row) {
        ans[k / c][k % c] = num;
        ++k;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int[][] matrixReshape(int[][] nums, int r, int c) {
    if (nums.length == 0 || r * c != nums.length * nums[0].length)
      return nums;

    int[][] ans = new int[r][c];
    int k = 0;

    for (int[] row : nums)
      for (final int num : row) {
        ans[k / c][k % c] = num;
        ++k;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def matrixReshape(self, nums: list[list[int]],
                    r: int, c: int) -> list[list[int]]:
    if nums == [] or r * c != len(nums) * len(nums[0]):
      return nums

    ans = [[0 for j in range(c)] for i in range(r)]
    k = 0

    for row in nums:
      for num in row:
        ans[k // c][k % c] = num
        k += 1

    return ans