[LeetCode] Set Mismatch

645. Set Mismatch

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
unordered_set<int> res;
for(int i = 1; i <= nums.size(); i++)
res.insert(i);

for(auto& num : nums) {
if(res.count(num))
res.erase(num);
else
res.insert(num);
}

return vector<int> (res.begin(), res.end());
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/02/PS/LeetCode/set-mismatch/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.