题目
在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。
给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。
如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should 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.
我的代码
class Solution:def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:prev_size = len(mat)*len(mat[0])after_size = r*cif(prev_size!=after_size):return matelse:lst = []sub_list = []count = 0for each_list in mat:for each_num in each_list:count+=1sub_list.append(each_num)if(count==c):lst.append(sub_list)count=0sub_list=[]return lst
思路
先考虑不符合转换规则的情况。
如果可以转换,则遍历matrix,用count记录每个sub_list里元素的数量。如果数量饱和则将sub_list并入lst中,并清空sub_list。
一个debug时发现的细节
此处sub_list=[] 不能用sub_list.clear()替代。
原因是sub_list=[]会创建一个新的空list,而sub_list.clear()会直接清空当前的sub_list, 由于 lst.append(sub_list)是直接将当前sub_list的地址放入,如果清空当前sub_list,则也会顺带清空lst里的值。
评论区中的python切片法
list-comprehension写法:
lst = [element[i] for i in range(0,n)]#相当于lst=[]for i in range(0,n):lst.append(element[i])
class Solution:def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:m,n=len(nums),len(nums[0])if m*n!=r*c:return nums# 将原矩阵转化成 1D array, list-comprehension一行搞定# 形式为res=[each_num,each_num,each_num...]# 即生成一个list,list内部由一个个each_num构成res=[each_num for sub_list in nums for each_num in sub_list]#理解方式,一个大list内含有多个res list,每个res中包含c个元素return [res[i:i+c] for i in range(0,len(res),c)]
注意:res[i:i+c]从res[i]开始,不包含res[i+c],同 in range规范一样
