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
In this Java method, a linear index is computed from a 2D original index and instantly redistributes into the reshaped matrix, managing access through calculated transformations.