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