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 == matrix0.length
  • 1 <= m, n <= 200
  • -231 <= matrixij <= 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
相关推荐
学无止境小袁同学31 分钟前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴1 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
LK_072 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk5552 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
Pniubi2 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK2 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
用户54817845909503 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
文丑颜不良啊3 小时前
LeetCode3341~3360题目解析
java·leetcode
yiangL_3 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互