Leetcode #566. Reshape the Matrix

本文介绍了一种模拟MATLAB中重塑矩阵功能的方法,利用Python实现将一个二维数组按指定行列数重塑成新矩阵,同时提供了两种简洁有效的实现思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.

题意

这道题就是希望模拟MATLAB中对软件进行变形,变成指定行列的新矩阵

想法

其实这个解法也是很简单的模拟,使用一个暂存列表来保存新行元素,通过判断是不是达到指定列长来决定是不是加到结果列表中。而且比较友好的是它给定的是二维数组,如果是多维的话,我可能会考虑用递归去遍历得到元素,但比较痛苦的便是最后你要组成元素了。。。可以当成升级版来想
然后我反思一下简单版里我的做法,我的做法一开始还用了if-else来判断是不是生成了足够的元素,但后来交完后看到这个做法是不够简洁的,其实只用一个if判断列表生成足够元素后加进结果集就可以了,反思一下。还有一种比较简洁的做法就是从行的角度来考虑,以行r为遍历下标,每次取r*c到(r+1)*c的元素填充进去,这个用到了列表的slicing和extend,就比较简洁,连判断也不用了。

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        if (len(nums)==r and len(nums[0])==c) or (len(nums)*len(nums[0])!=r*c):
            return nums
        result = list()
        # tmp = list()
        # cnt = 0
        # for i in range(len(nums)):
        #     for j in range(len(nums[i])):
        #         tmp.append(nums[i][j])
        #         cnt += 1
        #         if cnt == c:
        #             result.append(tmp)
        #             tmp = list()
        #             cnt = 0
        # return result
        num1 = list()
        for i in range(len(nums)):
            num1.extend(nums[i])
        for time in range(r):
            result.append(num1[time*c: (time+1)*c])
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值