Leetcode 73. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

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

Example 2:

Input: 
[
  [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]
]

Follow up:

  • A straight forward 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。
  • 需要注意把首行首列提前检查,避免混淆。
 1 class Solution:
 2     def setZeroes(self, matrix: List[List[int]]) -> None:
 3         """
 4         Do not return anything, modify matrix in-place instead.
 5         """
 6         first_row, first_col = False, False
 7         
 8         # check the first row and column first
 9         for i in range( len( matrix ) ):
10             if matrix[i][0] == 0:
11                 first_col = True;
12                 break;
13                 
14         for i in range( len( matrix[0] ) ):
15             if matrix[0][i] == 0:
16                 first_row = True;
17                 break;
18                 
19         # use the first row and column as marker
20         for i in range( 1, len( matrix ) ):
21             for j in range( 1, len( matrix[0] ) ):
22                 if matrix[i][j] == 0:
23                     matrix[i][0], matrix[0][j] = 0, 0;
24         
25         for i in range( 1, len( matrix ) ):
26             for j in range( 1, len( matrix[0] ) ):
27                 if matrix[i][0] == 0 or matrix[0][j] == 0:
28                     matrix[i][j] = 0
29                     
30         if first_row:
31             for i in range( len( matrix[0] ) ):
32                 matrix[0][i] = 0;
33                 
34         if first_col:
35             for i in range( len( matrix ) ):
36                 matrix[i][0] = 0;
View Code

 

 

posted on 2019-07-03 19:20  浩然119  阅读(129)  评论(0编辑  收藏  举报