先展成一维数组,再映射成 r 行 c 列 数组
写法一:class Solution(object):
def matrixReshape(self, mat, r, c):
"""
:type mat: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if not mat:
return []
row_mat = len(mat)
col_mat = len(mat[0])
res = []
all_num = [] # note : res = all_num = [] # error ! 这样写会占用同一块存储空间
if row_mat * col_mat == r * c:
for i in range(row_mat):
for j in range(col_mat):
all_num.append(mat[i][j]) # 展成一维数组,即 flatten *** 作
tmp = []
for k in range(row_mat * col_mat):
tmp.append(all_num[k])
if (k + 1) % c == 0:
res.append(tmp)
tmp = []
else:
return mat
return res
写法二:(简洁版)
class Solution(object):
def matrixReshape(self, mat, r, c):
m, n = len(mat), len(mat[0])
if m * n != r * c:
return mat
ans = [[0] * c for _ in range(r)]
for x in range(m * n):
ans[x // c][x % c] = mat[x // n][x % n]
return ans
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)