【leetcode系列】【算法】【中等】矩阵置零

题目:

题目链接: https://leetcode-cn.com/problems/set-matrix-zeroes/

解题思路:

方法一(O(m + n)的空间复杂度):

添加两个set变量,在遍历时,保存需要置零的行列号

然后根据两个set变量,再次遍历数组,进行置零操作

方法二(O(1)的空间复杂度):

在遍历时,如果遇到[i][j]位置为0,则将[i][0]和[0][j]两个位置设置为0,标记需要置零的行列

再次遍历时,根据这个标志位,进行置零操作

这个方法需要注意的地方是:

如果第一行没有0,但是第二行第一个为0,会导致再次遍历时,认为第一行需要置0,而进行了误操作

所以需要额外添加一个变量,进行标记第一行是否需要进行置零操作

代码实现:

方法一:

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        row_lst, column_lst = set(), set()
        for i in range(0, len(matrix)):
            for j in range(0, len(matrix[0])):
                if matrix[i][j] == 0:
                    row_lst.add(i)
                    column_lst.add(j)
                    
        for i in range(0, len(matrix)):
            if i in row_lst:
                matrix[i] = [0] * len(matrix[i])
            else:
                for j in column_lst:
                    matrix[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.
        """
        is_col = False
        R = len(matrix)
        C = len(matrix[0])
        for i in range(R):
            # Since first cell for both first row and first column is the same i.e. matrix[0][0]
            # We can use an additional variable for either the first row/column.
            # For this solution we are using an additional variable for the first column
            # and using matrix[0][0] for the first row.
            if matrix[i][0] == 0:
                is_col = True
            for j in range(1, C):
                # If an element is zero, we set the first element of the corresponding row and column to 0
                if matrix[i][j]  == 0:
                    matrix[0][j] = 0
                    matrix[i][0] = 0

        # Iterate over the array once again and using the first row and first column, update the elements.
        for i in range(1, R):
            for j in range(1, C):
                if not matrix[i][0] or not matrix[0][j]:
                    matrix[i][j] = 0

        # See if the first row needs to be set to zero as well
        if matrix[0][0] == 0:
            for j in range(C):
                matrix[0][j] = 0

        # See if the first column needs to be set to zero as well        
        if is_col:
            for i in range(R):
                matrix[i][0] = 0
发布了100 篇原创文章 · 获赞 4 · 访问量 1489

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105236146
今日推荐