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
相关推荐
Flittly3 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling7 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook10 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风12 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风12 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm