题目
在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
示例 1
输入:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
输出:
[[1,2,3,4]]
解释:
行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵,
用之前的元素值一行一行填充新矩阵。
示例 2
输入:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
输出:
[[1,2],
[3,4]]
解释:
没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。
注意
给定矩阵的宽和高范围在 [1, 100]。
给定的 r 和 c 都是正数。
思路
- 将nums里面的元素按照行排列的顺序存到一个新的list L中
- 判断r*c是否等于L的长度,如果不等于直接返回原来的nums。否则按照r行c列的方式存储。代码如下:
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
L = []
X = []
Y = []
count = 0
for x in nums:
for y in x:
L.append(y)
lens = len(L)
if lens < r*c :
return nums
for i in range(r):
for j in range(c):
X.append(L[count])
count = count+1
Y.append(X)
X = []
return Y
学习他人代码
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if not nums or not nums[0]: #判断nums是否为空
return []
if r * c != len(nums) * len(nums[0]):
return nums #reshape判断是否可行且合理,否则返回原矩阵
res = []
sub = []
for i in nums:
sub.extend(i) #extend用于在一个列表后加入另一个列表的元素
i = 0
while i < len(sub):
res.append(sub[i:i+c])
i += c
return res