給定奇數 N 和 N 個整數,其中必有一個數出現次數 ≥ (N+1)/2。求該數(眾數)。多測試用例,EOF 結束。
出現次數超過一半的元素,在任意兩兩抵消(不同元素配對消除)後必然留下。這是 Boyer-Moore 多數投票算法的基礎。
candidate = 0, count = 0。
#include <cstdio>
int main() {
int n, x;
while (scanf("%d", &n) == 1) {
int candidate = 0, cnt = 0;
for (int i = 0; i < n; ++i) {
scanf("%d", &x);
if (cnt == 0) { candidate = x; cnt = 1; }
else if (x == candidate) ++cnt;
else --cnt;
}
printf("%d\n", candidate);
}
return 0;
}
O(N),單次掃描。O(1),僅常數變量。優於哈希表計數(O(N) 空間)和排序法(O(N log N) 時間)。