见转载帖子的回复部分:
http://blog.csdn.net/v_july_v/article/details/6890054
#include<iostream>
#include <stdio.h>
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( a[i] == candidate )
ntimes++;
else
ntimes--;
}
int ctimes;
int candidate2 = a[n - 1];
for( i = ctimes = 0; i < n; i++ )
{
if( a[i] == candidate )
ctimes++;
}
return ctimes == n /2 ? candidate : candidate2;
}
}
int main()
{
int a[]={ 1,1,3,4,1,1,2,2 };
cout<<find(a,sizeof(a)/sizeof(int))<<endl;
// int a[6]={1,0,2,1,2,1};
// cout<<Find(a,6)<<endl;
}