LeetCode第566题:重塑矩阵(python)

题目:
在这里插入图片描述

思路:
利用两个新的空数组去做,首先设立一个临时存储数组this_nums,和一个汇总数组new_nums
遍历mat的行列,并把mat的每个值按顺序加入到this_nums中,并判断this_nums的长度是否等于给定的列长c,如果等于就把this_nums加入到new_nums中,并清空this_nums。

代码如下:

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        row = len(mat)
        col = len(mat[0])

        if row * col != r * c:
            return mat

        this_nums = []
        new_nums = []
        for i in range(row):
            for j in range(col):
                # 将mat里的数值依次加入this_nums中
                this_nums.append(mat[i][j])
                # 当this_nums的长度等于规定列数时
                if len(this_nums) == c:
                    # 将this_nums加入new_nums,并清空this_nums
                    new_nums.append(this_nums)
                    this_nums = []

        return new_nums
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值