73. 矩阵置零

73. 矩阵置零

  • 题目
  • 示例
  • [1. 两个set存储横纵坐标](#1. 两个set存储横纵坐标)

题目

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。

示例

示例 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]]

提示:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -231 <= matrix[i][j] <= 231 - 1

进阶:

一个直观的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。

一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。

你能想出一个仅使用常量空间的解决方案吗?

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/set-matrix-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1. 两个set存储横纵坐标

执行用时:28 ms, 在所有 Python 提交中击败了69.77%的用户

内存消耗:13.5 MB, 在所有 Python 提交中击败了88.37%的用户

通过测试用例:170 / 170

python 复制代码
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        lm,lmm = len(matrix), len(matrix[0])
        # 两个set,分别装坐标x和y
        sx = set()
        sy = set()
        # 遍历寻找需要为0的横纵
        for i in range(lm):
            for j in range(lmm):
                if matrix[i][j] == 0:
                    sx.add(i)
                    sy.add(j)
        # 部署零
        for i in range(lm):
            for j in range(lmm):
                if i in sx or j in sy:
                    matrix[i][j] = 0
相关推荐
花酒锄作田1 小时前
使用 pkgutil 实现动态插件系统
python
灵感__idea2 小时前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
前端付豪5 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽5 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战6 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋11 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
Wect12 小时前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript
NAGNIP1 天前
一文搞懂深度学习中的通用逼近定理!
人工智能·算法·面试
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python