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

                

            

        

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: