力扣: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
相关推荐
Zhen (Evan) Wang3 分钟前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
我爱一条柴ya7 分钟前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程
赶紧去巡山32 分钟前
pyhton基础【23】面向对象进阶四
python
旷世奇才李先生1 小时前
PyCharm 安装使用教程
ide·python·pycharm
这里有鱼汤1 小时前
“对象”?对象你个头!——Python世界观彻底崩塌的一天
后端·python
尘浮7281 小时前
60天python训练计划----day59
开发语言·python
wh39331 小时前
使用Python将PDF转换成word、PPT
python·pdf·word
三维重建-光栅投影2 小时前
VS中将cuda项目编译为DLL并调用
算法
船长@Quant2 小时前
数学视频动画引擎Python库 -- Manim Voiceover 语音服务 Speech Services
python·数学·manim·动画引擎·语音旁白
好开心啊没烦恼3 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas