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
相关推荐
985小水博一枚呀1 小时前
【深度学习|可视化】如何以图形化的方式展示神经网络的结构、训练过程、模型的中间状态或模型决策的结果??
人工智能·python·深度学习·神经网络·机器学习·计算机视觉·cnn
CyreneSimon1 小时前
使用 LoRA 进行模型微调的步骤
python·transformer
ymchuangke1 小时前
数据清洗-缺失值处理-缺失值可视化图(竖线)
python·算法·数学建模
我要学编程(ಥ_ಥ)2 小时前
滑动窗口算法专题(1)
java·数据结构·算法·leetcode
计算机学姐2 小时前
基于python+django+vue的旅游网站系统
开发语言·vue.js·python·mysql·django·旅游·web3.py
程序员小羊!2 小时前
Python语言基础教程(下)4.0
开发语言·python
LluckyYH2 小时前
代码随想录Day 46|动态规划完结,leetcode题目:647. 回文子串、516.最长回文子序列
数据结构·人工智能·算法·leetcode·动态规划
源代码:趴菜3 小时前
LeetCode118:杨辉三角
算法·leetcode·动态规划
luluvx3 小时前
LeetCode[中等] 74.搜索二维矩阵
算法·leetcode·矩阵