Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
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?
Set Matrix Zeroes
題目本身很簡(jiǎn)單,最簡(jiǎn)單的方式是記錄下每個(gè)有0的row和column,然后通過(guò)go through 一遍就可以,while ,如果所有的element都是0的話,那space就是m*n
但是可以通過(guò)一種很巧妙的方法規(guī)避掉額外空間
因?yàn)榈谝粋€(gè)row和column終歸會(huì)變成0如果他所在的column or row有0存在,那我們?yōu)槭裁床挥胒irst row 和first column來(lái)記錄呢
0 | 1 | 1 | 0 | 1 |
---|---|---|---|---|
1 | ||||
0 | ||||
1 |
每當(dāng)我們看到一個(gè)0的時(shí)候,我們就可以martix[i][0] = 0, matrix[0][j] = 0
后面的時(shí)候我們只需要每次查看element當(dāng)前的row or column是否是 0,如果是的話我們就martix[i][j] = 0,
具體實(shí)現(xiàn)看代碼
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
r ,c = 1,1
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
if i == 0:
r = 0
if j == 0:
c = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print(matrix)
if(matrix[i][0] == 0 or matrix[0][j] == 0):
matrix[i][j] = 0
if not r:
matrix[0] = [0]*len(matrix[0])
if not c:
for i in range(len(matrix)):
matrix[i][0] = 0