[leecode]Python:566. Reshape the Matrix 重塑矩阵

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.

解析:将数组按照给定的行数和列数对数组进行重新排列
要求:数组原先的元素个数要与给定的行数列数的乘积相等,否则无法转换
思路:将数组的元素拿出来单独放到一个一维数组,然后再将数组插回去
代码如下:
92ms

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

观看提交记录有一个非常不错的提交

import collections
class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        d = collections.deque(sum(nums,[]))
        if r*c != len(nums)*len(nums[0]):
            return nums
        else:
            return [[d.popleft() for i in range(c)] for j in range(r)]

将stack的数组转化为队列deque,然后在当中取数,这样子代码简洁了很多。很棒

猜你喜欢

转载自blog.csdn.net/weixin_36637463/article/details/87967045