python leetcode 重塑矩阵【简单题】

1. 读懂题目

2. 分析,推导解法,产生思路。

解题思路:(1)逐行遍历放在对应的位置

(2)转换为一维数组;除法问题找到对应位置 。

除法问题:已知第i个元素,求在r行c列矩阵中的位置?  即为i/c行和i%c列

(3)直接调用python numpy 中的内置函数 reshape 。但运行时间和空间都很高,不推荐。

3.代码实现

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        # 逐行遍历放在对应的位置
        # 给定参数的reshape不合理
        if r * c != len(nums)* len(nums[0]):
            return nums
        # 合理,新建矩阵并放置元素
        nums_new = []
        row = 0
        col = 0
        for i in range(r):
            temp_list = []
            for j in range(c):
                temp_list.append(nums[row][col])
                if col == len(nums[0])-1:   # 之前的矩阵行遍历结束
                    col = 0
                    row +=1
                else:
                    col += 1                # 继续遍历之前矩阵的行
            nums_new.append(temp_list)
        return nums_new

    def matrixReshape1(self, nums, r, c):
        # 转换为一维数组;除法问题找到对应位置
        # 除法问题:已知第i个元素,求在r行c列矩阵中的位置?
        # 即为i/c行和i%c列
        row = len(nums)
        col = len(nums[0])
        if r * c != row * col :
            return nums
        res = [[0]*c for _ in range(r)]     # 新建一个r行c列矩阵
        for x in range(r * c):
            # 处理第i个元素,找到之前矩阵与新矩阵的元素并赋值
            res[x//c][x%c] = nums[x//col][x%col]
        return res

    def matrixReshape2(self, nums, r, c):
        # python numpy 中的内置函数 reshape
        # 运行时间和空间都很高,不推荐
        if r * c != len(nums)* len(nums[0]):
            return nums
        import numpy as np
        # 直接调用内置函数
        return np.asarray(nums).reshape(r,c)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值