TypeScript Dominator
function dominator(a: number[]): number {
let size = 0;
let value = 0;
let index = 0;
a.forEach((v, k) => {
if (size === 0) {
size++;
value = v;
index = k;
} else if (value !== v) {
size--;
} else {
size++;
}
});
const candidate = size > 0 ? value : -1;
let count = 0;
for (const v of a) {
if (v === candidate) {
count++;
}
}
if (count <= a.length / 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.