自学内容网 自学内容网

LeetCode 73 Set Matrix Zeroes 题目解析和python代码

题目:
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s.

You must do it in place.

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]]

Constraints:

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

Follow up:

A straightforward 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?

题目解析:
我们首先找到哪一行或者哪一列有0存在,然后我们把那一整行或那一整列修改成0。

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        m, n = len(matrix), len(matrix[0])

        first_row_has_zero = any(matrix[0][j]==0 for j in range(n))
        first_col_has_zero = any(matrix[i][0]==0 for i in range(m))

# 遍历除了第一行和第一列的所有元素,如果发现有元素等于0,就把对应的第一行和第一列的元素设置为0。
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0 
                    matrix[0][j] = 0
        
        # 找到第一行和第一列的0元素,把一整行或一整列设置为0。
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    print(f"Second for loop - i: {i}, j: {j}")
                    matrix[i][j] = 0
                    print(f"Second for loop: {matrix}")
        
        # 检查第一行或第一列是否本身就含有0。
        if first_row_has_zero:
            for j in range(n):
                matrix[0][j] = 0
                print(f"Third for loop: {matrix}")

        if first_col_has_zero:
            for i in range(m):
                matrix[i][0] = 0
                print(f"Forth for loop: {matrix}")
        


遍历除了第一行和第一列的所有元素,如果发现有元素等于0,就把对应的第一行和第一列的元素设置为0。

[1, 1, 1],
[1, 0, 1],
[1, 1, 1]

例如,我们发现位置(1,1)的元素是0,我们就把位置(0,1)的元素和位置(1,0)的元素设置为0。

[1, 0, 1],
[0, 0, 1],
[1, 1, 1]

找到第一行和第一列的0元素,把一整行或一整列设置为0。
例如,上面这个matrix,我们发现 i = 1 and j = 1时, matrix[1][0] == 0,因此我们设置 matrix[1][1] = 0。

[1, 0, 1], 
[0, 0, 1], 
[1, 1, 1]

接着 i = 1 and j = 2时,matrix[1][0] == 0,因此我们设置 matrix[1][2] = 0。

[1, 0, 1], 
[0, 0, 0], 
[1, 1, 1]

接着 i = 2 and j = 1时,matrix[0][1] == 0,因此我们设置 matrix[2][1] = 0。

[1, 0, 1], 
[0, 0, 0], 
[1, 0, 1]

我们利用第一行和第一列作为marker,来标记所有的0。

time complexity 是O(m * n)。
space complexity 是O(1)。


原文地址:https://blog.csdn.net/weixin_57266891/article/details/142760076

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!