C++ Dominator
#include <cstddef>
#include <vector>
int dominator(const std::vector<int>& a)
{
int size = 0;
int value = 0;
int index = 0;
for (std::size_t k = 0; k < a.size(); ++k) {
int v = a[k];
if (size == 0) {
++size;
value = v;
index = static_cast<int>(k);
} else if (value != v) {
--size;
} else {
++size;
}
}
int candidate = size > 0 ? value : -1;
int count = 0;
for (int v : a) {
if (v == candidate) {
++count;
}
}
if (count <= static_cast<int>(a.size()) / 2) {
index = -1;
}
return index;
}
This finds a value that appears in more than half of the array, then returns one valid index for it.