題目:數組中有一個數字出現的次數超過了數組長度的一半,找出這個數字。
詳見《編程之美》的2.3尋找發帖水王。
#include <iostream>
using namespace std;
int Find(int *a, int N)//出現次數超過一半的數字
{
int candidate;
int nTimes, i;
for(i=nTimes=0; i<N; i++)
{
if(nTimes==0)
{
candidate=a[i];
nTimes=1;
}
else
{
if(candidate==a[i])
nTimes++;
else
nTimes--;
}
}
return candidate;
}
void main()
{
int a[5]={0,1,2,1,1};
cout<<Find(a, 5)<<endl;
}