力扣: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
相关推荐
kimnoic11 分钟前
Python操作xlwings的实例详解
开发语言·python
2601_9578838415 分钟前
2026年10月 外星人笔记本维修须知
python·电脑
泡茶喝茶写代码23 分钟前
A股量化数据工程:从 REST 接口到策略信号(第 17 篇):创新高与新低扫描
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
All for pursuit.24 分钟前
【动态规划-6】96.不同的二叉搜索树
数据结构·c++·算法·leetcode·动态规划
rou34 分钟前
Attention(注意力机制)
算法
VIP_CQCRE36 分钟前
用 Ace Data Cloud 接入 OpenAI 兼容语音转文字:一份能直接运行的 API 指南
python·openai·api·语音识别·acedatacloud
信奥卷王1 小时前
[GESP202609 六级] 数组划分
数据结构·算法
牧羊人.3331 小时前
动手学深度学习 07|Resnet网络与迁移学习
网络·人工智能·深度学习·神经网络·算法·cnn·迁移学习
砚底藏山河2 小时前
python量化入门:多周期数据对齐统一时间轴
java·数据库·python·金融·maven
All for pursuit.2 小时前
【并查集-2】399.除法求值
数据结构·c++·算法·leetcode