力扣: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
相关推荐
卷无止境1 小时前
Python能做嵌入式开发吗?一份写给动手派的生态与硬件全景图
后端·python
月光船幽幽5 小时前
检测用户意图复杂性的关键方法
人工智能·python
鹿角片ljp8 小时前
LeetCode 236. 二叉树的最近公共祖先|递归后序
算法
luj_17688 小时前
大律师考核应重能力与科技素养
c语言·开发语言·c++·经验分享·算法
无定义_8 小时前
Floyd——Warshall
算法
刃神太酷啦8 小时前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb
威联通网络存储8 小时前
TS-h3087XU-RP 汽车零部件质检追溯部署
python·汽车
你驴我8 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
IT毕设实战小研8 小时前
基于安卓的空气质量查询系统
android·大数据·vue.js·爬虫·python·django·课程设计
带多刺的玫瑰9 小时前
Leecode#9刷题之回文数
数据结构·算法