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
相关推荐
这个人懒得名字都没写4 小时前
Python包管理新纪元:uv
python·conda·pip·uv
有泽改之_4 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER4 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
是毛毛吧5 小时前
边打游戏边学Python的5个开源项目
python·开源·github·开源软件·pygame
三途河畔人5 小时前
Pytho基础语法_运算符
开发语言·python·入门
长安er5 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢5 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
CoderYanger6 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节
独行soc6 小时前
2025年渗透测试面试题总结-275(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
菜鸟233号7 小时前
力扣513 找树左下角的值 java实现
java·数据结构·算法·leetcode