cpp: add “645. Set Mismatch”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
8d4eb729b4
commit
1266061643
1 changed files with 33 additions and 0 deletions
33
cpp/set-mismatch.cpp
Normal file
33
cpp/set-mismatch.cpp
Normal 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;
|
||||||
|
}
|
Loading…
Reference in a new issue