主序元素

#include<stdio.h>

int majority(int R[],int n)
{
    int c,count=1,i;
    c=R[0];
    for(i=1;i<n;i++)
    {
        if(c==R[i])
            count++;
        else
        {
            if(count>0)
              count--;
            else
            {
                c=R[i];
                count=1;
            }
        }
    }
    if(count<=0)
        return -1;
    else
        for(count=0,i=0;i<n;i++)
            if(c==R[i])
                count++;

    if(count>n/2)
        return c;
    else 
        return -1;
}

void main()
{
    int R[100];
    int i,n,r;
    scanf("%d",&n);
    for(i=0;i<n;i++)
        scanf("%d",&R[i]);
    r=majority(R,n);
    if(r==-1)
        printf("can not find!\n");
    else
        printf("the majority element: %d\n",r);

}


你可能感兴趣的:(主序元素)