mycode
空间复杂度 m+n
思路:用set把为0元素所在行、列记录下来
注意:注释的方法更快
class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ rows = set() cols = set() count_row = len(matrix) count_col = len(matrix[0]) for i in range(count_row): for j in range(count_col): if matrix[i][j] == 0: rows.add(i) cols.add(j) #for row in rows: # matrix[row] = [0]*count_col #for col in cols: # for line in matrix: # line[col] = 0 for i in rows: for j in xrange(count_col): matrix[i][j] = 0 for i in xrange(count_row): for j in cols: matrix[i][j] = 0 return matrix
参考:
常数空间,用第一行第一列来记录
class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ first_row = False first_col = False m = len(matrix) n = len(matrix[0]) #[[]] if m == 0 or n == 0 : return flag = -1 for i in range(m): if matrix[i][0] == 0: #说明第一列本来最后就应该都等于0,以免被覆盖 first_col = True for j in range(n): if matrix[0][j] == 0: first_row = True for i in range(1,m): for j in range(1,n): if matrix[i][j] == 0: matrix[i][0] = matrix[0][j] = 0 #第一行所有列,第一列所有行 为对照表,所以节省了空间 for i in range(1,m): for j in range(1,n): if matrix[0][j] == 0 or matrix[i][0] == 0: matrix[i][j] = 0 if first_row: for j in range(n): matrix[0][j] = 0 if first_col: for i in range(m): matrix[i][0] = 0