力扣:73. 矩阵置零(Python3)

题目:

给定一个 mxn 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法**。**

来源:力扣(LeetCode)

链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

输入:matrix = \[1,1,1,1,0,1,1,1,1]

输出:\[1,0,1,0,0,0,1,0,1]

示例 2:

输入:matrix = \[0,1,2,0,3,4,5,2,1,3,1,5]

输出:\[0,0,0,0,0,4,5,0,0,3,1,0]

解法:

使用1行和1列记录哪些行哪些列需要置0。

代码:

python 复制代码
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        row = []
        col = []
        for indexr, r in enumerate(matrix):
            for indexc, c in enumerate(r):
                if c == 0:
                    if indexr not in row:
                        row.append(indexr)
                    if indexc not in col:
                        col.append(indexc)
        for r in row:
            matrix[r] = [0] * len(matrix[0])
        for c in col:
            for r in range(len(matrix)):
                matrix[r][c] = 0
相关推荐
timeDifference₇3 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu4 小时前
python:DecisionTree
开发语言·后端·python·算法
怒放的生命19915 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu5 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
fengkai45456 小时前
Python运维
运维·python·监控·psutil·ipy
Fancy.7616 小时前
:Python条件与循环语句学习总结
python
AllData公司负责人8 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
Wellijohn8 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python
新*8 小时前
标题全变成一级?靠编号规律找回章节边界
python·正则表达式·pdf解析·文本处理