题目描述:给定一个原来的数组,再给出新的r和c,要求将原数组转换成新的rc大小的数组
题目思路:
一、我自己的思路:
step1:如果rc不等于原本数组的大小,也就是不能互相转换,则返回原本的数组
step2: 考虑两个数组如何建立对应关系(mapping)。从一个2d数组转换到1d数组的关系是:
x = i*c + j
那么从1d转换为2d的关系是:
i = x//c(商)
j = x%c(余数)
由此得到两个矩阵的变换对应关系
step3: 开始编码
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
r_ori = len(nums)
c_ori = len(nums[0])
if c_ori*r_ori != r*c:
return nums
r3_num = [[nums[(j*c+i)//c_ori][(j*c+i)%c_ori] for i in range(c)] for j in range(r)]
return r3_num
用到的知识:
python列表生成器:
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431779637539089fd627094a43a8a7c77e6102e3a811000
好像就是这个方法是最好的了,而且有生之年我的代码也是挺简洁的卧槽。