LeetCode 题解工作台

矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法 。 示例 1: 输入: matrix = [[1,1,1],[1,0,1],[1,1,1]] 输出: [[1,0,1],[0,0,0],[1,0,1]] 示例 2: 输入: matrix …

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

Let the number of rows and columns of the matrix be and , respectively. We use an array of length and an array of length to record which rows and columns need to be set to zero. First, we travers…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法

 

示例 1:

输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]

示例 2:

输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

 

提示:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -231 <= matrix[i][j] <= 231 - 1

 

进阶:

  • 一个直观的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。
  • 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
  • 你能想出一个仅使用常量空间的解决方案吗?
lightbulb

解题思路

Solution 1: Array Marking

Let the number of rows and columns of the matrix be mm and nn, respectively. We use an array rows\textit{rows} of length mm and an array cols\textit{cols} of length nn to record which rows and columns need to be set to zero.

First, we traverse the matrix. When we find a zero element in the matrix, we set the corresponding row and column markers to true\text{true}. That is, if matrix[i][j]=0\textit{matrix}[i][j] = 0, then rows[i]=cols[j]=true\textit{rows}[i] = \textit{cols}[j] = \text{true}.

Finally, we traverse the matrix again and use the markers in rows\textit{rows} and cols\textit{cols} to update the elements in the matrix. When we find that rows[i]\textit{rows}[i] or cols[j]\textit{cols}[j] is true\text{true}, we set matrix[i][j]\textit{matrix}[i][j] to zero.

The time complexity is O(m×n)O(m \times n), and the space complexity is O(m+n)O(m + n). Here, mm and nn are the number of rows and columns of the matrix, respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        m, n = len(matrix), len(matrix[0])
        row = [False] * m
        col = [False] * n
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    row[i] = col[j] = True
        for i in range(m):
            for j in range(n):
                if row[i] or col[j]:
                    matrix[i][j] = 0
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you know how to modify a matrix in place without using additional space?

  • question_mark

    Can you explain how you would handle edge cases such as when the first row or column has zeros?

  • question_mark

    Will you optimize for space by using in-place modifications instead of extra memory?

warning

常见陷阱

外企场景
  • error

    Overwriting the first row or column while marking zeroed rows and columns can lead to incorrect results if not handled properly.

  • error

    Failing to correctly identify and handle edge cases, such as when the first row or column contains zeros.

  • error

    Using too much extra space when a more efficient in-place solution is possible.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if you were not allowed to use the first row and column to track the zero positions?

  • arrow_right_alt

    How would you solve this problem if the matrix could contain negative numbers?

  • arrow_right_alt

    Can you optimize this solution further to handle very large matrices, possibly with sparse zeros?

help

常见问题

外企场景

矩阵置零题解:数组·哈希·扫描 | LeetCode #73 中等