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
相关推荐
神仙别闹7 分钟前
基于Python+Neo4j实现新冠信息挖掘系统
开发语言·python·neo4j
navyDagger8 分钟前
GAN生成对抗网络数学原理解释并实现MNIST数据集生产(附代码演示)
人工智能·python
没有梦想的咸鱼185-1037-166311 分钟前
【降尺度】ChatGPT+DeepSeek+python+CMIP6数据分析与可视化、降尺度技术与气候变化的区域影响、极端气候分析
python·chatgpt·数据分析
OpenC++14 分钟前
【C++QT】Layout 布局管理控件详解
c++·经验分享·qt·leetcode
berryyan15 分钟前
傻瓜教程安装Trae IDE用AI撰写第一个AKShare接口脚本
python·trae
灏瀚星空32 分钟前
从基础到实战的量化交易全流程学习:1.3 数学与统计学基础——概率与统计基础 | 基础概念
笔记·python·学习·金融·概率论
Hellohistory37 分钟前
HOTP 算法与实现解析
后端·python
伊织code38 分钟前
cached-property - 类属性缓存装饰器
python·缓存·cache·装饰器·ttl·property·cached-property
1白天的黑夜11 小时前
贪心算法-860.柠檬水找零-力扣(LeetCode)
c++·算法·leetcode·贪心算法
明明跟你说过1 小时前
深度学习常见框架:TensorFlow 与 PyTorch 简介与对比
人工智能·pytorch·python·深度学习·自然语言处理·tensorflow