力扣2965. 找出缺失和重复的数字

题目:

给你一个下标从 0 开始的二维整数矩阵 grid,大小为 n * n ,其中的值在 1, n² 范围内。除了 a 出现两次,b 缺失 之外,每个整数都恰好出现一次 。

任务是找出重复的数字a 和缺失的数字 b 。

返回一个下标从 0 开始、长度为 2 的整数数组 ans,其中 ans0 等于a,ans1 等于b。

提示:

  • 2 <= n == grid.length == grid[i].length <= 50
  • 1 <= grid[i][j] <= n * n
  • 对于所有满足1 <= x <= n * nx ,恰好存在一个 x 与矩阵中的任何成员都不相等。
  • 对于所有满足1 <= x <= n * nx ,恰好存在一个 x 与矩阵中的两个成员相等。
  • 除上述的两个之外,对于所有满足1 <= x <= n * nx ,都恰好存在一对 i, j 满足 0 <= i, j <= n - 1grid[i][j] == x

思路:

用字典记录从1到n²的每个值出现的次数,键值对为数字:出现次数。然后在字典中找到值为0(缺失)或2(重复)对应的键即可。代码如下:

python 复制代码
class Solution:
    def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
        n = len(grid)
        ans = [0, 0]
        num_dict = {i:0 for i in range(1, n*n+1)}   # 数字:出现次数
        # 遍历矩阵,更新字典中的值
        for row in grid:
            for num in row:
                num_dict[num] += 1
        # 找到字典中值为0或2对应的键
        for key, values in num_dict.items():
            if values == 2:
                ans[0] = key
            if values == 0:
                ans[1] =key
        return ans

提交通过:

相关推荐
金銀銅鐵2 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup116 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi008 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵10 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf11 小时前
Agent 流程编排
后端·python·agent
copyer_xyf11 小时前
Agent RAG
后端·python·agent
copyer_xyf12 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf12 小时前
Agent 记忆管理
后端·python·agent
JieE21219 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试