Leetcode - 73. Set Matrix Zeroes

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
题目本身很简单,最简单的方式是记录下每个有0的row和column,然后通过go through 一遍就可以,while ,如果所有的element都是0的话,那space就是m*n

但是可以通过一种很巧妙的方法规避掉额外空间

因为第一个row和column终归会变成0如果他所在的column or row有0存在,那我们为什么不用first row 和first column来记录呢

0 1 1 0 1
1
0
1

每当我们看到一个0的时候,我们就可以martix[i][0] = 0, matrix[0][j] = 0

后面的时候我们只需要每次查看element当前的row or column是否是 0,如果是的话我们就martix[i][j] = 0,

具体实现看代码

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

你可能感兴趣的:(Leetcode - 73. Set Matrix Zeroes)