LeetCode 题解工作台
找出缺失和重复的数字
给你一个下标从 0 开始的二维整数矩阵 grid ,大小为 n * n ,其中的值在 [1, n 2 ] 范围内。除了 a 出现 两次 , b 缺失 之外,每个整数都 恰好出现一次 。 任务是找出重复的数字 a 和缺失的数字 b 。 返回一个下标从 0 开始、长度为 2 的整数数组 ans ,其中 …
4
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们创建一个长度为 $n^2 + 1$ 的数组 ,统计矩阵中每个数字出现的次数。 接下来遍历 $i \in [1, n^2]$,如果 $cnt[i] = 2$,则 是重复的数字,我们将答案的第一个元素设为 ;如果 $cnt[i] = 0$,则 是缺失的数字,我们将答案的第二个元素设为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的二维整数矩阵 grid,大小为 n * n ,其中的值在 [1, n2] 范围内。除了 a 出现 两次,b 缺失 之外,每个整数都 恰好出现一次 。
任务是找出重复的数字a 和缺失的数字 b 。
返回一个下标从 0 开始、长度为 2 的整数数组 ans ,其中 ans[0] 等于 a ,ans[1] 等于 b 。
示例 1:
输入:grid = [[1,3],[2,2]] 输出:[2,4] 解释:数字 2 重复,数字 4 缺失,所以答案是 [2,4] 。
示例 2:
输入:grid = [[9,1,7],[8,9,2],[3,4,6]] 输出:[9,5] 解释:数字 9 重复,数字 5 缺失,所以答案是 [9,5] 。
提示:
2 <= n == grid.length == grid[i].length <= 501 <= grid[i][j] <= n * n- 对于所有满足
1 <= x <= n * n的x,恰好存在一个x与矩阵中的任何成员都不相等。 - 对于所有满足
1 <= x <= n * n的x,恰好存在一个x与矩阵中的两个成员相等。 - 除上述的两个之外,对于所有满足
1 <= x <= n * n的x,都恰好存在一对i, j满足0 <= i, j <= n - 1且grid[i][j] == x。
解题思路
方法一:计数
我们创建一个长度为 的数组 ,统计矩阵中每个数字出现的次数。
接下来遍历 ,如果 ,则 是重复的数字,我们将答案的第一个元素设为 ;如果 ,则 是缺失的数字,我们将答案的第二个元素设为 。
时间复杂度 ,空间复杂度 。其中 是矩阵的边长。
class Solution:
def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
n = len(grid)
cnt = [0] * (n * n + 1)
for row in grid:
for v in row:
cnt[v] += 1
ans = [0] * 2
for i in range(1, n * n + 1):
if cnt[i] == 2:
ans[0] = i
if cnt[i] == 0:
ans[1] = i
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n^2) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Efficiently applies array scanning combined with hash lookup for problem-solving.
- question_mark
Handles edge cases such as the smallest grid and missing number properly.
- question_mark
Uses mathematical tricks for sum or square comparisons in a clever manner.
常见陷阱
外企场景- error
Not using an efficient hash table approach or array scanning pattern.
- error
Missing the condition that exactly one number repeats, which can confuse the detection logic.
- error
Overcomplicating the solution by introducing unnecessary algorithms or extra space usage.
进阶变体
外企场景- arrow_right_alt
Handling different grid sizes and ensuring the algorithm scales well.
- arrow_right_alt
Applying the method to non-square grids or matrices.
- arrow_right_alt
Exploring alternative methods that don’t involve hashing, such as sorting or indexing.