[LeetCode] Find Missing and Repeated Values

2965. Find Missing and Repeated Values

You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2]. Each integer appears exactly once except a which appears twice and b which is missing. The task is to find the repeating and missing numbers a and b.

Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> findMissingAndRepeatedValues(vector<vector<int>>& A) {
unordered_set<int> us;
unordered_map<int, int> mp;
int n = A.size();
vector<int> res{0,0};
for(int i = 1; i <= n * n; i++) us.insert(i);
for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) {
mp[A[i][j]] += 1;
if(mp[A[i][j]] == 2) res[0] = A[i][j];
us.erase(A[i][j]);
}
res[1] = *begin(us);
return res;
}
};


Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/17/PS/LeetCode/find-missing-and-repeated-values/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.