【Leetcode】python - [73] Set Matrix Zeroes 個人解法筆記

題目出處

73. Set Matrix Zeroes

難度

medium

個人範例程式碼

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        hash_column = set()
        hash_row = set()

        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == 0:
                    hash_column.add(i)
                    hash_row.add(j)

        for i in list(hash_column):
            for j in range(len(matrix[0])):
                 matrix[i][j] = 0

        for i in range(len(matrix)):
            for j in list(hash_row):
                 matrix[i][j] = 0

算法說明

用兩組 row, column 的 hashset 去儲存有 0 的 column, row,
最後再依照 hashset 裡面儲存的內容,更新矩陣內容為 0。

input handling

題目沒有特別要求

Boundary conditions

用兩層 for loop 來控制範圍

Reference