Sponsored
Sponsored
This approach involves two main steps: flattening the original matrix into a one-dimensional array and then reconstructing it into the desired dimensions. The flattening process collects all elements by iterating row-wise over the original matrix. Then, if the total number of elements matches the product of new dimensions r
and c
, the method distributes these elements row-wise into the new matrix. If the element count does not match, the original matrix is returned.
Time Complexity: O(m * n) where m and n are the dimensions of the original matrix.
Space Complexity: O(r * c) for the reshaped matrix.
1public class Solution {
2 public int[][] MatrixReshape(int[][] mat, int r, int c) {
3 int m = mat.Length, n = mat[0].Length;
4 if (m * n != r * c) return mat;
5
6 int[][] newMat = new int[r][];
7 for (int i = 0; i < r; i++)
8 newMat[i] = new int[c];
9
10 for (int i = 0; i < m * n; i++) {
11 newMat[i / c][i % c] = mat[i / n][i % n];
12 }
13 return newMat;
14 }
15}
16
The C# solution constructs a new array structure by distributing original matrix elements according to indices derived from the flattened representation. The method first verifies the compatibility of dimensions.
Index Mirroring leverages mathematical transformation to directly address elements from the original matrix into the new shape without explicitly flattening. It avoids extra space for a flat array and directly computes 2D indices in the new layout.
Time Complexity: O(m * n).
Space Complexity: O(r * c) for storing reshaped matrix.
1def
Python’s approach involves nested loops iterating the original matrix, directly moving each element to a calculated destination in the new matrix using linear indexing equivalence.