Problem: a matrix is presented as a list of lists. Set the whole row/column zero if an element is zero. The problem is not difficult. It can be done by a list or a set. My timer indicates that the list is faster than a set. I remember that the mechanism of searching an element in a set is, like a hashtable, faster than in a list (Correct me if I am wrong). Is my matrix too small?
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix) # number of rows
n = len(matrix[0]) # number of columns
row_z = [] # row/column numbers with a zero in the original matrix
col_z = []
#row_z = set()
#col_z = set()
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
row_z += [i]
col_z += [j]
#row_z.add(i)
#col_z.add(j)
for i in row_z:
for j in range(n):
matrix[i][j] = 0
for i in range(m):
for j in col_z:
matrix[i][j] = 0