LeetCode 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 crepresenting 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.

题目分析及思路

给定一个二维矩阵和想要得到的新矩阵的行数和列数,返回新矩阵。新矩阵要被原矩阵的所有元素填满,且如果得不到新矩阵,则返回原矩阵。可以将原矩阵的元素放在一个列表中,然后根据所给行数和列数对该列表进行拆分。

python代码

class Solution:

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

        rows, cols = len(nums), len(nums[0])

        if rows * cols != r * c:

            return nums

        else:

            matrix_list = []

            for row in nums:

                matrix_list.extend(row)

            new_matrix1 = []

            new_matrix2 = []

            for idx in range(r):

                for i in range(0+idx*c,c+idx*c):

                    new_matrix1.append(matrix_list[i])

                new_matrix2.append(new_matrix1)

                new_matrix1 = []

            return new_matrix2

                

            

        

 

posted on 2019-03-05 09:28  锋上磬音  阅读(176)  评论(0编辑  收藏  举报