73. 矩阵置零


思路

先获取元素为0所在的行和列,用集合rows 存放元素为0的行,集合cols存放元素为0的列

遍历矩阵,遇到的行、列为0元素所在行、列,将对应行、列的元素设置为0

ps:用集合可以去重、用in时时间复杂度O(1)

python 复制代码
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        rows=set()
        cols=set()
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):
                if matrix[i][j]==0:
                    rows.add(i)
                    cols.add(j)
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):
                if i in rows:
                    matrix[i][j]=0
                else:
                    if j in cols:
                        matrix[i][j]=0
        return matrix
相关推荐
weixin_377634845 分钟前
【python异步多线程】异步多线程爬虫代码示例
开发语言·爬虫·python
struggle202520 分钟前
PennyLane 是一个用于量子计算、量子机器学习和量子化学的跨平台 Python 库。由研究人员构建,用于研究
python·量子计算
扑克中的黑桃A20 分钟前
Python-素数
python
扑克中的黑桃A21 分钟前
Python学习的自我理解和想法(4)
python
扑克中的黑桃A30 分钟前
Python-打印杨辉三角(进阶版)
python
laity171 小时前
激活IDM的几种方法
python
gsls2008081 小时前
使用xdocreport导出word
前端·python·word
Watink Cpper2 小时前
[灵感源于算法] 算法问题的优雅解法
linux·开发语言·数据结构·c++·算法·leetcode
Johny_Zhao2 小时前
基于CentOS Stream 8的物联网数据采集与展示方案
linux·网络·python·mqtt·mysql·网络安全·信息安全·云计算·shell·yum源·系统运维
这里有鱼汤2 小时前
想成为下一个吉姆·西蒙斯,这十种经典K线形态你一定要记住
后端·python