leetcode 566. Reshape the Matrix( Python )

383 阅读22分钟

描述

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.

Note:

The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.

解析

根据题意将结果分为两部分,如果 指定的 r 和 c 是不合法的那就输出原数组,如果合法那就按照 r 行 c 列输出 nums 数组。这里就是遍历 nums 数组, 直接给结果数组赋值即可。时间复杂度 O(m * n),m 和 n 是指 nums 的行数和列数,空间复杂度为 O(m * n), 主要是用于 m ∗ n 的结果值。

解答

class Solution(object):
def matrixReshape(self, nums, r, c):
    """
    :type nums: List[List[int]]
    :type r: int
    :type c: int
    :rtype: List[List[int]]
    """
    row = len(nums)
    col = len(nums[0])
    result = [[0]*c for _ in range(r)]
    count = 0
    if row * col != 0 and row * col == r*c:
        rows = 0
        cols = 0
        for i in range(row):
            for j in range(col):
                result[rows][cols] = nums[i][j]
                cols += 1
                if cols==c:
                    rows += 1
                    cols = 0
        return result
                
    else:
        return nums
            

运行结果

Runtime: 84 ms, faster than 73.32% of Python online submissions for Reshape the Matrix.
Memory Usage: 12.8 MB, less than 79.14% of Python online submissions for Reshape the Matrix.	

每日格言:每个人都有属于自己的一片森林,迷失的人迷失了,相逢的人会再相逢。

感谢支持 支付宝

支付宝

微信

微信