33,008
社区成员
发帖
与我相关
我的任务
分享
int majority(int* a, int n)
{
int candidate = a[0], count = 1;
for(int i=1;i<n;i++)
{
if(count == 0) candidate = a[i];
if(a[i] == candidate) count++;
else count--;
}
count = 0;
for(int i=0;i<n;i++)
if(candidate == a[i]) count++;
return count > n/2 ? candidate : 0;
}