美文网首页
每天(?)一道Leetcode(13) Set Matrix Z

每天(?)一道Leetcode(13) Set Matrix Z

作者: 失业生1981 | 来源:发表于2019-01-27 21:51 被阅读0次

Array

073. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

即将矩阵中0元素所在的行和列的所有元素都换为0
example:
Input:
\left[ \begin{matrix} 1 & 1 & 1 \\ 1 & 0 & 1 \\ 1 & 1 & 1 \end{matrix} \right]

Output:
\left[ \begin{matrix} 1 & 0 & 1 \\ 0 & 0 & 0 \\ 1 & 0 & 1 \end{matrix} \right]

Solutions:

把0元素的行和列分别存起来,遍历完所有元素后,将存起来的行、列元素置为0

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

相关文章

网友评论

      本文标题:每天(?)一道Leetcode(13) Set Matrix Z

      本文链接:https://www.haomeiwen.com/subject/pbwnjqtx.html