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.
1import java.util.Arrays;
2
3public class Solution {
4 public int[][] matrixReshape(int[][] mat, int r, int c) {
5 int m = mat.length, n = mat[0].length;
6 if (m * n != r * c) return mat;
7
8 int[][] newMat = new int[r][c];
9 for (int i = 0; i < m * n; i++) {
10 newMat[i / c][i % c] = mat[i / n][i % n];
11 }
12 return newMat;
13 }
14}
15
The Java implementation iterates through each element of the original matrix, using modular arithmetic for index calculation. If the dimensions don't match, the original matrix is returned. Otherwise, it assembles the new matrix using in-place element assignment.
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.
1#include <vector>
2using namespace std;
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int m = mat.size(), n = mat[0].size();
if (m * n != r * c) return mat;
vector<vector<int>> newMat(r, vector<int>(c));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int index = i * n + j;
newMat[index / c][index % c] = mat[i][j];
}
}
return newMat;
}
This C++ code maintains element continuity via index coordination. Element addresses transition between matrices of differing dimensions by recalculating new indices without pre-flattening.