73. Set Matrix Zeroes
problem description
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]
]algorithm thought
这个题目不是很难,但是LeetCode限制了我们,希望我们使用O(1)的空间复杂度,然后DO IT IN-PLACE。于是我将第一行和第一列定义为标志位,从2行2列开始遍历,如果为0,将为0的那行和列的第一位设置为0标志位。之后再次遍历一遍第一行和第一列,将有标志位的那一行或者一列置为零
code
algorithm analysis
这类题目,无论你算法多么巧妙,时间复杂度都会是O(n²),但是这里空间复杂度被限制到了O(1),有很大提升。
Last updated