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.
1#include <vector>
2using namespace std;
3
4vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
5 int m = mat.size(), n = mat[0].size();
6 if (m * n != r * c) return mat;
7
8 vector<vector<int>> newMat(r, vector<int>(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
The C++ solution operates similarly to the C solution, using vector data structures for dynamic array management. The transformation is performed directly via element access and indexing based on a linear flattening concept.
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.
1public class Solution {
public int[][] MatrixReshape(int[][] mat, int r, int c) {
int m = mat.Length, n = mat[0].Length;
if (m * n != r * c) return mat;
int[][] newMat = new int[r][];
for (int i = 0; i < r; ++i) {
newMat[i] = new 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;
}
}
C# implementation mirrors elements from the original matrix into a new reindexed formation. It uses calculated indices to determine positions in the transformed space without intermediate data flattening.