题目要求:
给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reshape-the-matrix
自己的题解:
直接暴力填空,先将原始矩阵变为1维列表,然后按照重构矩阵的行列进行遍历填空
时间复杂度为O(rc),空间复杂度为O(rc)
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
rows_in=0
cols_in=0
if len(nums)!=0:
rows_in=len(nums)
if len(nums[0])!=0:
cols_in=len(nums[0])
if r*c!=rows_in*cols_in:
return nums
else:
nums_one=[]
for i in range (rows_in):
nums_one=nums_one+nums[i]
out_martix=[]
for i in range (r):
out_martix_col=[]
for j in range (c):
out_martix_col.append(nums_one[i*c+j])
out_martix.append(out_martix_col)
return out_martix
官方的题解:
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
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reshape-the-matrix/solution/zhong-su-ju-zhen-by-leetcode-solution-gt0g/
来源:力扣(LeetCode)