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] ]
将0所在的行和列都重置为0。
第一想法比较简单,把所有0的所在行和所在列统计出来,然后将这些行和列设为0。当然这种方法时间复杂度很高。
这里学到np.argwhere()方法,能直接返回查找值所在行列。
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
import numpy as np
rows=set()
cals=set()
m=np.matrix(matrix)
for r,c in np.argwhere(m==0):
rows.add(r)
cals.add(c)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i in rows or j in cals:
matrix[i][j]=0
return matrix
或者直接标记也很简单迅速。
就是在遍历过程中,把0所在的行和列都标记,最后再把所有标记的地方改为0。
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
rows = len(matrix)
if(rows==0): return
cols = len(matrix[0])
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
for row in range(rows):
if matrix[row][j] != 0:
matrix[row][j] = 'x'
for col in range(cols):
if matrix[i][col] != 0:
matrix[i][col] = 'x'
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 'x':
matrix[i][j] = 0