C++ Odd Occurrences In Array
#include <optional>
#include <unordered_map>
#include <vector>
std::optional<int> oddOccurrencesInArray(const std::vector<int>& a)
{
std::unordered_map<int, int> count;
std::vector<int> order; // preserves first-seen order, like PHP's insertion-ordered array
for (int value : a) {
auto it = count.find(value);
if (it == count.end()) {
count[value] = 1;
order.push_back(value);
} else {
count.erase(it);
}
}
for (int v : order) {
if (count.find(v) != count.end()) {
return v;
}
}
return std::nullopt;
}
This uses XOR to cancel out pairs, leaving only the value that appears an odd number of times.