KK's blog

每天积累多一些

0%

LeetCode 073 Set Matrix Zeroes

LeetCode



Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0‘s, and return the matrix.

You must do it in place.

Example 1:



Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]


Example 2:



Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]


Constraints:

m == matrix.length n == matrix[0].length
1 <= m, n <= 200 -2<sup>31</sup> <= matrix[i][j] <= 2<sup>31</sup> - 1

Follow up:

A straightforward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution.
* Could you devise a constant space solution?

题目大意:

若矩阵某元素为0,设置它所在的行和列所有元素均为0,不能用额外区间

解题思路:

用第0行和第0列作为统计。由于第0行和第0列会被覆盖,所以先查看他们有无0

解题步骤:

N/A

注意事项:

  1. 用第0行和第0列作为统计。由于第0行和第0列会被覆盖,所以先查看他们有无0。两大步骤:先统计,再根据结果设置0
  2. 第二步中,根据第0和和第0列的结果回设,均从1开始,不含左上cell,因为统计结果不保存在它上。它仅在统计第一行和第一列是否有0时用到。

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def setZeroes(self, matrix: List[List[int]]) -> None:
# calculate
is_zero_row_zero = True if len([0 for n in matrix[0] if n == 0]) > 0 else False
is_zero_col_zero = True if len([0 for i in range(len(matrix)) if matrix[i][0] == 0]) > 0 else False
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0], matrix[0][j] = 0, 0
# Set
for i in range(1, len(matrix)): # remember to start with 1
if matrix[i][0] == 0:
for j in range(1, len(matrix[0])):
matrix[i][j] = 0
for j in range(1, len(matrix[0])): # remember to start with 1
if matrix[0][j] == 0:
for i in range(1, len(matrix)):
matrix[i][j] = 0
if is_zero_row_zero:
for j in range(len(matrix[0])):
matrix[0][j] = 0
if is_zero_col_zero:
for i in range(len(matrix)):
matrix[i][0] = 0

算法分析:

时间复杂度为O(n2),空间复杂度O(1)

Free mock interview