码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 73. Set Matrix Zeroes

时间:2019-07-03 19:45:59      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:mod   color   input   problems   org   blank   closed   lan   for   

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

 

 

Leetcode 73. Set Matrix Zeroes

标签:mod   color   input   problems   org   blank   closed   lan   for   

原文地址:https://www.cnblogs.com/pegasus923/p/11128473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!