566. Reshape the Matrix矩阵重排

[抄题]:

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道怎么用程序语言写出来

[一句话思路]:

形象思考一下:先加col,再加row

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

nums[0]是指同一列

[一刷]:

  1. 不会写重排:col满了之后,直接清0就行

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

重排:col满了之后,直接清0就行

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

重排

if (col == c) {
                    col = 0;
                    row++;
                }

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        //ini
        int m = nums.length;
        int n = nums[0].length;
        int[][] result = new int[r][c];
        
        //cc
        if (m * n != r * c) {
            return nums;
        }
        
        //for loop,add
        int col = 0;
        int row = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                result[row][col] = nums[i][j];
                col++;
                
                if (col == c) {
                    col = 0;
                    row++;
                }
            }
        }
        
        //return res
        return result;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8878089.html