leetcode-mid-array-73 set matrix zeros

mycode

Space complexity of m + n

Idea: set to 0 by the elements in the row, column recorded

Note: Note the method is faster

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

reference:

Constant space, with a first column of the first row to the record

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):
            ifMatrix [I] [0] == 0: # Description Finally it should have been the first column are equal to zero, to avoid being covered 
                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
         # a first row of all columns, the first table of all behavior, so saving space 
        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

 

Guess you like

Origin www.cnblogs.com/rosyYY/p/10963786.html