水王问题及扩展

来源:互联网 发布:瓷砖销售软件破解版 编辑:程序博客网 时间:2024/05/22 13:01


int findEle(int a[],int len){    int candidate;    int nTimes=0;    for(int i=0;i<len;i++)    {        if(nTimes==0)        {            candidate=a[i];            nTimes=1;        }        else        {            if(candidate==a[i])                nTimes++;            else                nTimes--;        }    }return candidate;}



用candidate[3]记录三个候选ID,用count[3]记录它们的累积次数,然后遍历整个ID列表,每处理一个ID,若与candidate[i]中的某一个相同,则count[i]++,若与三个都不同,则说明找到了四个互不相同的ID,将三个count[i]--,也就相当于“删除了四个不同ID”,若某一个count[i]==0,则更新之。


int nTimes[3]={1};int candidate[3];        candidate[0]=a[0];        candidate[1]=a[1];        candidate[2]=a[2];        for(int i=1;i<len;i++)        {                if(candidate[0]==a[i])                        nTimes[0]++;                else if(candidate[1]==a[i])                        nTimes[1]++;                else if(candidate[2]==a[i])                        nTimes[2]++;                else if(nTimes[0]==0)                {                        candidate[0]=a[i];                        nTimes[0]=1;                }                else if(nTimes[1]==0)                {                        candidate[1]=a[i];                        nTimes[1]=1;                }                else if(nTimes[2]==0)                {                        candidate[2]=a[i];                        nTimes[2]=1;                }                else                {                        nTimes[0]--;                        nTimes[1]--;                        nTimes[2]--;                }        }




0 0
原创粉丝点击