LeetCode ASMR: Convert 1D Array Into 2D Array | Day 74 Coding Chill

แชร์
ฝัง
  • เผยแพร่เมื่อ 2 พ.ย. 2024

ความคิดเห็น • 1

  • @LeekCodeDev
    @LeekCodeDev  2 หลายเดือนก่อน +2

    Source Code:
    class Solution:
    def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
    '''
    To solve this problem, we can create a new 2D array with
    the given dimensions, iterate through the original array
    and put those values from the original array onto
    our new 2d array as we iterate through it. We can quickly
    identify an invalid array by taking a look at the number of
    elements the original array has. If the given dimensions
    (row by column) total arrays doesn't equal the length
    of the original array (total arrays), that means that
    the size will be invalid :D
    '''
    if len(original) != (m*n):
    return []
    new_arr = [[0]*n for _ in range(m)]
    counter = 0
    for i in range(m):
    for j in range(n):
    new_arr[i][j] = original[counter]
    counter += 1
    return new_arr