LeetCode #566. Reshape the Matrix
题目
解题方法
先判断能否reshape,如果可以再把原数组拆成一个一维数组,之后按照rc重新放置即可。
时间复杂度:O(rc)
空间复杂度:O(r*c)
代码
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
if len(nums[0]) * len(nums) != r * c:
return nums
numsarr = []
for i in range(len(nums)):
numsarr += nums[i]
cur_pos = 0
matrix = []
for i in range(r):
cur_row = []
for j in range(c):
cur_row.append(numsarr[cur_pos])
cur_pos += 1
matrix.append(cur_row)
return matrix

浙公网安备 33010602011771号