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 number of rows and the number of columns 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]]
Example 2:
Input: mat = [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
就是把矩阵变成r行c列的矩阵,按row遍历的顺序。就,非常直观的一道题,但是刚开始还是没在草稿纸上画一下就在瞎写导致index出错了。首先是按row col遍历的时候求它在矩阵中按row遍历的index,应该是i * col + j,毕竟一个row有col个元素。然后是最后通过index求具体哪行哪列的时候也是要针对col进行/和%。别的没啥了。
Runtime: 1 ms, faster than 89.95% of Java online submissions for Reshape the Matrix.
Memory Usage: 51 MB, less than 20.94% of Java online submissions for Reshape the Matrix.
- class Solution {
- public int[][] matrixReshape(int[][] mat, int r, int c) {
- if (mat.length * mat[0].length != r * c) {
- return mat;
- }
- int[][] result = new int[r][c];
- for (int i = 0; i < r; i++) {
- for (int j = 0; j < c; j++) {
- int index = i * c + j;
- result[i][j] = mat[index / mat[0].length][index % mat[0].length];
- }
- }
- return result;
- }
- }