566. 重塑矩阵
在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
解题
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
1.构成矩阵的基本条件:元素相等
if len(nums)*len(nums[0]) == r*c:
pass
else:
return nums
2.构造新的矩阵,并在遍历过程中把元素添加到新矩阵中
res = [[]*r]
count, c0, r0 = 0, 0, 0
while count < r*c:
while c0 < c:
res[r0].append(nums[count//len(nums[0])][count%len(nums[0])])
c0 += 1
count += 1
c0 = 0
r0 += 1
return res
完整代码
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
if len(nums)*len(nums[0]) == r*c:
res = [[]*r]
count, c0, r0 = 0, 0, 0
while count < r*c:
while c0 < c:
res[r0].append(nums[count//len(nums[0])][count%len(nums[0])])
c0 += 1
count += 1
c0 = 0
r0 += 1
return res
else:
return nums
精简优化版本
1.对重复使用的变量赋值
2.构造完整的矩阵结构
3.添加元素的方式不在用append,而是在矩阵具备完整结构的条件下一一赋值
4.记得空行
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
ans = [[0] * c for _ in range(r)]
for x in range(m * n):
ans[x // c][x % c] = nums[x // n][x % n]
return ans