矩阵置零

矩阵置零

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

输入: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
输出: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

输入: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
输出: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

O(m+n):用row, col记录下来行和列中有无零,最后将该行该列置零

class Solution:
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        m = len(matrix)
        n = len(matrix[0])
        
        row = [False] * m
        col = [False] * n
        
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    row[i] = True
                    col[j] = True
        
        for i in range(m):
            if row[i]:
                for j in range(n):
                    matrix[i][j] = 0
        for j in range(n):
            if col[j]:
                for i in range(m):
                    matrix[i][j] = 0
        
        print(matrix)
        return

O(1):用首行首列存储row,col,用额外两个bool变量存储首行首列是否有零,只占用O(1)空间

class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        first_row = False
        first_col = False
        m = len(matrix)
        n = len(matrix[0])
        # 第一列若有0,first_col = True
        for i in range(m): 
            if matrix[i][0] == 0:
                first_col = True
        # 第一行若有0,first_row = True
        for j in range(n):
            if matrix[0][j] == 0:
                first_row = True
        # 若中间有0,同时映射到首行首列
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][j] == 0:
                    matrix[i][0] = matrix[0][j] = 0
        # 然后通过首行首列,将所有改为0的置为0
        for i in range(1, m):
            for j in range(1, n):
                if matrix[0][j] == 0 or matrix[i][0] == 0:
                    matrix[i][j] = 0
        # 最后再把保存好的首行首列是否改为0的信息拿出来置为0
        if first_row:
            for j in range(n):
                matrix[0][j] = 0
        if first_col:
            for i in range(m):
                matrix[i][0] = 0
    原文作者:momo1023
    原文地址: https://www.jianshu.com/p/43b6a23134f8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞