力扣: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
相关推荐
cup111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi003 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵5 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf6 小时前
Agent 流程编排
后端·python·agent
copyer_xyf6 小时前
Agent RAG
后端·python·agent
copyer_xyf6 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf7 小时前
Agent 记忆管理
后端·python·agent
JieE21214 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python