Leetcode 题解记录-566 重塑矩阵-reshape martix

题目要求:

给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。

重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。

如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reshape-the-matrix


自己的题解:

直接暴力填空,先将原始矩阵变为1维列表,然后按照重构矩阵的行列进行遍历填空

时间复杂度为O(rc),空间复杂度为O(rc)

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        rows_in=0
        cols_in=0
        if len(nums)!=0:
            rows_in=len(nums)
            if len(nums[0])!=0:
                cols_in=len(nums[0])
        if r*c!=rows_in*cols_in:
            return nums
        else:
            nums_one=[]
            for i in range (rows_in):
                nums_one=nums_one+nums[i]
            out_martix=[]
            for i in range (r):
                out_martix_col=[]
                for j in range (c):
                    out_martix_col.append(nums_one[i*c+j])
                out_martix.append(out_martix_col)
            return out_martix

官方的题解:

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

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reshape-the-matrix/solution/zhong-su-ju-zhen-by-leetcode-solution-gt0g/
来源:力扣(LeetCode)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值