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
标签:Matrix,nums,int,Reshape,矩阵,566,new,row,matrix 来源: https://www.cnblogs.com/yao1996/p/10474709.html