If we cannot fit all elements of original in the grid, we return empty.
Otherwise, say we have already copied elements from the
original. Then the next element would be at index of the
original. If we translate into grid coordinates,
. In other words,
original[k] corresponds to grid[count-copied-rows * row-width][count-copied-columns].
We can copy by grid: or by original:
.
By grid
For the cell we copy the number at the index
of the
original.
Time: , space:
.
from itertools import product as cartesian
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
two_d = [
[0] * n for _ in range(m)
]
for r, c in cartesian(range(m), range(n)):
i = r*n + c
two_d[r][c] = original[i]
return two_d
By original
We copy into
.
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
two_d = [
[0] * n for _ in range(m)
]
for i, x in enumerate(original):
r, c = divmod(i, n)
two_d[r][c] = x
return two_d
Leave a comment