1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

cpp: add “645. Set Mismatch”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-01-22 11:34:43 +01:00
parent 8d4eb729b4
commit 1266061643
Signed by: mfocko
GPG key ID: 7C47D46246790496

33
cpp/set-mismatch.cpp Normal file
View file

@ -0,0 +1,33 @@
#include <cassert>
#include <unordered_set>
#include <vector>
class Solution {
public:
std::vector<int> findErrorNums(const std::vector<int> &nums) {
int expected_sum = nums.size() * (1 + nums.size()) / 2;
int sum = 0;
int unique_sum = 0;
std::unordered_set<int> seen;
seen.reserve(nums.size());
for (const int x : nums) {
sum += x;
if (!seen.contains(x)) {
unique_sum += x;
}
seen.insert(x);
}
return {sum - unique_sum, expected_sum - unique_sum};
}
};
int main() {
Solution s;
assert((s.findErrorNums(std::vector{1, 2, 2, 4}) == std::vector{2, 3}));
assert((s.findErrorNums(std::vector{1, 1}) == std::vector{1, 2}));
return 0;
}