leetcode 566. Reshape the Matrix( Python )

描述

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.php

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.ios

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:less

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:yii

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:svg

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 的結果值。ui

解答

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.	
複製代碼

每日格言:每一個人都有屬於本身的一片森林,迷失的人迷失了,相逢的人會再相逢。es5

感謝支持
支付寶

支付寶

微信

微信
相關文章
相關標籤/搜索