566. 重塑矩阵

题目描述

 在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
 给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
 重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
 如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

原题请参考链接https://leetcode-cn.com/problems/reshape-the-matrix/

题解

方法一 【暴力破解】

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        row = len(nums)
        if row == 0:
            return []
        col = len(nums[0])
        if row * col != r*c:
            return nums
        num = []
        for i in range(row):
            for j in range(col):
                num.append(nums[i][j])
        f = 0
        nums = []
        for i in range(r):
            ans = []
            for j in range(c):
                ans.append(num[f])
                f += 1
            nums.append(ans)
        return nums

方法二 【数学】

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        m, n = len(nums), len(nums[0])
        if m * n != r * c:
            return nums
        
        ans = [[0] * c for _ in range(r)]
        for x in range(m * n):
            ans[x // c][x % c] = nums[x // n][x % n]
        
        return ans
posted @ 2021-02-17 21:41  Bladers  阅读(71)  评论(0)    收藏  举报