13 - Medium - 矩阵置零

2018-04-19  本文已影响0人  1f872d1e3817

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

示例 1:

输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
</pre>

示例 2:

输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]</pre>

进阶:

空间复杂度O(m + n),分别用两个list记录0的行列

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

常数空间,用matrix 的首行首列记录其余行的0的情况

class Solution:
    # @param matrix, a list of lists of integers
    # @return nothing (void), do not return anything, MODIFY matrix IN PLACE.
    def setZeroes(self, matrix):
        if len(matrix) == 0:
            return ;
        row, col = 1, 1
        for i in range(0, len(matrix)):
            if matrix[i][0] == 0:
                col = 0
        for j in range(0, len(matrix[0])):
            if matrix[0][j] == 0:
                row = 0
        
        for i in range(1, len(matrix)):
            for j in range(1, len(matrix[0])):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0
        for i in range(1, len(matrix)):
            for j in range(1, len(matrix[0])):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0
                    
        if col == 0:
            for i in range(0, len(matrix)):
                matrix[i][0] = 0
        if row == 0:
            for j in range(0, len(matrix[0])):
                matrix[0][j] = 0
上一篇 下一篇

猜你喜欢

热点阅读