【Leetcode】python - [566] Reshape the Matrix 個人解法筆記 (內含範例程式碼) 內含 array 初始化, index 操作與控制範例

題目出處

566. Reshape the Matrix

難度

Easy

題目分類

array

個人範例程式碼

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        total = m*n
        if total != r*c :
            return mat
        else:
            ans = [[0] * c for _ in range(r)] # count to c, then add one r
            for idx in range(total):
            # origin matrix = [idx//n][idx%n] # which y, and which x
            # notice: [idx//n][idx%n] not m,n
            # after matrix = [idx//n][idx%c] # which y, and which x
            # notice: [idx//c][idx%c] not r,c (r -> auto add axis)
                ans[idx//c][idx%c] = mat[idx//n][idx%n]
            return ans

Time Complexity

O(mn)

算法說明

先判斷是否元素數量相等,
再來去進行移動動作,用 index 去巧妙控制他。

corner case 特殊情況處理

元素數量不相等時,直接回傳原來的答案。

Boundary conditions/ Edge conditions 邊際情況處理

這題可以練習 array 初始化與位置操作相關的技巧,

array 初始化

二維陣列的初始化,
我們可以記憶:

  • 從第一維的 [0] 開始複製,「複製 c 次」完成第一維,
  • 這個動作要「重複做 r 次」,完成複製 r 維。
ans = [[0] * c for _ in range(r)] # count to c, then add one r

元素 index 操作與控制

這裡有個元素 index 操作的技巧,
當我們已經知道所有元素的內容皆會被使用,
而我們只是要單純控制輸出方式時,
像這題中,我們可以發現邏輯上,
我們都是「先完成第一維後,再新增一維

以這題來說,有另外一個 index 操作技巧,
我們先有「完成一層後,才新增一層」的概念,
因此我們可以很容易用「%」、「//」取餘數、整除,
來獲得相對應的位置。

for idx in range(total):
            # origin matrix = [idx//n][idx%n] # which y, and which x
            # notice: [idx//n][idx%n] not m,n
            # after matrix = [idx//c][idx%c] # which y, and which x
            # notice: [idx//c][idx%c] not r,c (r -> auto add axis)
                ans[idx//c][idx%c] = mat[idx//n][idx%n]

特別注意:取的座標為 「//n」、「%n」,而非 m, n,
因為我們真正「決定是否換行、與現在座標餘數」的,都只有 n 。

Reference