0%

Leetcode - 2022 with python

前言

紀錄一下解決 Leetcode 第 2022 題的過程

我們先來看題目 - Convert 1D Array Into 2D Array

題目

You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.

The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.

Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.

Example 1:

Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
Explanation: The constructed 2D array should contain 2 rows and 2 columns.
The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.
The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.

Example 2:

Input: original = [1,2,3], m = 1, n = 3
Output: [[1,2,3]]
Explanation: The constructed 2D array should contain 1 row and 3 columns.
Put all three elements in original into the first row of the constructed 2D array.

Example 3:

Input: original = [1,2], m = 1, n = 1
Output: []
Explanation: There are 2 elements in original.
It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.

Constraints:

  • 1 <= original.length <= 5 * 104
  • 1 <= original[i] <= 105
  • 1 <= m, n <= 4 * 104

簡單來說題目要我們把它給定的 original 這個一維陣列,根據 m 還有 n 的值轉換成對應的二維陣列
不能轉換的就直接回傳空陣列

解題過程

一開始我們先排除掉不能轉換的,怎樣叫不能轉換,就是那些數量不剛好的就不能轉換
接著就可以去慢慢塞了,塞甚麼?
我們直接把陣列一段一段切片,切成題目規定的大小(n),然後切 m

1
2
3
4
5
6
7
8
9
10
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
result = []
if len(original) != m * n:
return result

for i in range(m):
result.append(original[i*n: (i+1)*n])

return result

切片中,我們用數學的方式來運算,起點必定是 **第幾次 乘上 所需大小(i*n)**,而終點必須+1,確保可以完整切到(如果妳不知道為甚麼,去看看 python 切 list,自己做一次就知道了)


如果有錯誤的部份,歡迎指正,謝謝。
如果你喜歡這篇文章,請幫我拍手
只需要註冊會員就可以囉,完全不用花費任何一毛錢就可以用來鼓裡創作者囉