1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/cpp/set-mismatch.cpp

34 lines
791 B
C++
Raw Normal View History

#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;
}