这道题思路比较简单,比较容易想到的是先判断m和n构成的二维数组在形式上是否可以由原来的数组转变而成,若不可以返回空数组,若可以直接用一个二重循环遍历一遍即可,时间复杂度 O ( n 2 ) O(n^2) O(n2)
class Solution(object):
def construct2DArray(self, original, m, n):
"""
:type original: List[int]
:type m: int
:type n: int
:rtype: List[List[int]]
"""
ans = [[0] * n for _ in range(m)]
if m * n != len(original):
return []
elif m == 1:
return [original]
else:
count = 0
for i in range(m):
for j in range(n):
ans[i][j] = original[count]
count += 1
return ans
题解的写法更为简洁,设original的长度为k,根据题意,如果k≠m*n则无法构成二维数组,此时返回空数组。否则我们可以遍历original,每n个元素创建一个一维数组,放入二维数组中
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return [original[i: i + n] for i in range(0, len(original), n)] if len(original) == m * n else []