首先明白什么是主元素,一个整数序列,相同元素的个数大于序列元素的一半就是主元素,,另外元素取值不大于元素个数
下面是算法实现:
#include<cstdio>
const int maxn=50;
int M[maxn],n;
int majorcount(int M[],int n)
{
int temp,count=1;//temp用来保存候选主元素
temp=M[0];//设置M[0]为候选主元素
for(int i=1;i<n;i++)
{
if(M[i]==temp)
{
count++;
}
else
{
if(count>0)
{
count--;
}
else
{
temp=M[i];
count=1;
}
}
}
if(count>0)
{
for(int i=0;i<n;i++)
{
if(M[i]==temp)
count++;
}
if(count>n/2)
{
printf("%d",temp);
}
else
{
printf("-1");
}
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&M[i]);
}
majorcount(M,n);
}