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 …
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
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 AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定一个 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.lengthn == matrix[0].length1 <= m, n <= 200-231 <= matrix[i][j] <= 231 - 1
进阶:
- 一个直观的解决方案是使用
O(mn)的额外空间,但这并不是一个好的解决方案。 - 一个简单的改进方案是使用
O(m + n)的额外空间,但这仍然不是最好的解决方案。 - 你能想出一个仅使用常量空间的解决方案吗?
解题思路
Solution 1: Array Marking
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 traverse the matrix. When we find a zero element in the matrix, we set the corresponding row and column markers to . That is, if , then .
Finally, we traverse the matrix again and use the markers in and to update the elements in the matrix. When we find that or is , we set to zero.
The time complexity is , and the space complexity is . Here, and are the number of rows and columns of the matrix, respectively.
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?