力扣: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
相关推荐
哥本哈士奇(aspnetx)20 小时前
Streamlit + LangChain 1.0 简单实现智能问答前后端
python·大模型
我一定会有钱20 小时前
斐波纳契数列、end关键字
python
fie888921 小时前
NSCT(非下采样轮廓波变换)的分解和重建程序
算法
小鸡吃米…21 小时前
Python 列表
开发语言·python
晨晖21 天前
单链表逆转,c语言
c语言·数据结构·算法
星依网络1 天前
yolov5实现游戏图像识别与后续辅助功能
python·开源·游戏程序·骨骼绑定
YoungHong19921 天前
面试经典150题[072]:从前序与中序遍历序列构造二叉树(LeetCode 105)
leetcode·面试·职场和发展
大佐不会说日语~1 天前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
2501_921649491 天前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融
qq_448011161 天前
python HTTP请求同时返回为JSON的异常处理
python·http·json