LeetCode 566. Reshape the Matrix
In MATLAB, there is a handy function called reshape
which can reshape an m x n
matrix into a new one with a different size r x c
keeping its original data.
You are given an m x n
matrix mat and two integers r and c representing the row number and column number of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix
.
Example 1:
Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
method
给出二维下标[i,j]
计算二维数组拉长的index
,公式为index = i * m + j
其中,m
是二维数组的列数,可以看出i
是index
除以m
的商,j
是余数
所以,用一维index
从二维数组中取值matrix[index / m][index % m]
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int m = mat.size(), n = mat[0].size();
if (r * c != m * n) return mat;
vector<vector<int>> res(r, vector<int>(c));
int idx = 0;
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
res[i][j] = mat[idx / n][idx % n];
idx++;
}
}
return res;
}