leetcode.array--73. Set Matrix Zeroes

来源:互联网 发布:suse 11 安装yum 编辑:程序博客网 时间:2024/06/04 14:09

题目:73. Set Matrix Zeroes

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

给定二维数组,将数组中出现0的行和列均置零,要求空间复杂度O(1)。第一遍遍历用第0行和第0列记录出现0的位置,记下第0行和第0列是否出现过0,第二遍遍历用来置零。这样时间复杂度为O(n^2)。

Python:

class Solution(object):    def setZeroes(self, matrix):        """        :type matrix: List[List[int]]        :rtype: void Do not return anything, modify matrix in-place instead.        """        rows=len(matrix)        cols=len(matrix[0])        firstRow,firstCol=False,False        for i in range(rows):            for j in range(cols):                if matrix[i][j]==0:                    if i==0:                        firstRow=True                    if j==0:                        firstCol=True                    matrix[0][j]=matrix[i][0]=0        for i in range(1,rows):            for j in range(1,cols):                if matrix[0][j]==0 or matrix[i][0]==0:                    matrix[i][j]=0        if firstCol:            for i in range(rows):                matrix[i][0]=0        if firstRow:            for i in range(cols):                matrix[0][i]=0        return


原创粉丝点击