今日题目

https://leetcode.com/problems/set-matrix-zeroes/

解题思路

本题要求将矩阵中存在 0 的行和列全部置零。因此,我们可以先记录所有含有 0 的行和列,再将这些行和列全部置零。

解题方法

  1. 记录所有含有 0 的行和列
  2. 将这些行和列全部置零

复杂度

  • 时间复杂度:$O(N \times M)$,N 为矩阵的行数,M 为矩阵的列数。

  • 空间复杂度:$O(N \times M)$,N 为矩阵的行数,M 为矩阵的列数。

代码

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

        change_row_idx = set([])
        change_col_idx = set([])
        # Note that here I use set to avoid recording the same row or column multiple times.

        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == 0:
                    change_row_idx.add(i)
                    change_col_idx.add(j)
        
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if i in change_row_idx or j in change_col_idx:
                    matrix[i][j] = 0

更多题解请访问 我的博客