Leetcode练习(Python):数组类:第73题:给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。

题目:
给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
思路:

进阶:

一个直接的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。
一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
你能想出一个常数空间的解决方案吗?

本例是使用额外空间为 O(m + n)的方法,之后会增加常数空间的解决方案。

程序:O(m + n)

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        row = len(matrix)
        column = len(matrix[0])
        auxiliary1 = [False] * column
        auxiliary2 = [False] * row
        for index1 in range(row):
            if 0 in matrix[index1]:
                auxiliary2[index1] = True
            for index2 in range(column):
                if matrix[index1][index2] == 0:
                    auxiliary1[index2] = True
        for index3 in range(row):
            if auxiliary2[index3] == True:
                for index4 in range(column):
                    matrix[index3][index4] = 0
        for index5 in range(column):
            if auxiliary1[index5] == True:
                for index6 in range(row):
                    matrix[index6][index5] = 0
posted on 2020-04-22 15:33  桌子哥  阅读(824)  评论(0编辑  收藏  举报