LeetCode-73 Set Matrix Zeroes

Description

Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.

Follow up:
• 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?

Constraints:
• m == matrix.length
• n == matrix[0].length
• 1 <= m, n <= 200
• -231 <= matrix[i][j] <= 231 - 1

Example

Example 1:
在这里插入图片描述
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:
在这里插入图片描述
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Submissions

这道题给定了一个 m x n 的矩阵,如果其中一个元素为 0,则将其所在行和列的所有元素都设为 0。我开始想到的是双层遍历矩阵,当元素为0即更改元素当前行列的所有元素。
代码如下:

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == 0:
                    for k in range(len(matrix[0])):
                                   matrix[i][k] = 0                   
                    for w in range(len(matrix)):
                                   matrix[w][j]=0

但如上这样做,前面的遍历修改操作会造成当遍历到后面元素时造成错误更改。因此遍历元素时只需要先标记当前行列值。当遍历结束后再进行元素修改即可。
实现代码如下:

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        m = len(matrix)
        n = len(matrix[0])
        row = [0 for _ in range(m)]
        col = [0 for _ in range(n)]      
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    row[i], col[j] = 1, 1                    
        for i in range(m):
            for j in range(n):
                if row[i] or col[j]:
                    matrix[i][j] = 0
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页