566. 重塑矩阵

566. 重塑矩阵

在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。

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

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

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

解题

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:

1.构成矩阵的基本条件:元素相等

		if len(nums)*len(nums[0]) == r*c:
			pass
		else:
            return nums

2.构造新的矩阵,并在遍历过程中把元素添加到新矩阵中

            res = [[]*r]
            count, c0, r0 = 0, 0, 0
            while count < r*c:
                while c0 < c:
                    res[r0].append(nums[count//len(nums[0])][count%len(nums[0])])
                    c0 += 1
                    count += 1
                c0 = 0
                r0 += 1
            return res

完整代码

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        if len(nums)*len(nums[0]) == r*c:
            res = [[]*r]
            count, c0, r0 = 0, 0, 0
            while count < r*c:
                while c0 < c:
                    res[r0].append(nums[count//len(nums[0])][count%len(nums[0])])
                    c0 += 1
                    count += 1
                c0 = 0
                r0 += 1
            return res
        else:
            return nums

精简优化版本

1.对重复使用的变量赋值
2.构造完整的矩阵结构
3.添加元素的方式不在用append,而是在矩阵具备完整结构的条件下一一赋值
4.记得空行

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Grayson Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值