问题描述:
Tango是微软亚洲研究院的一个试验项目。研究院的员工和实习生们都很喜欢在Tango上面交流灌水。传说,Tango有一大“水王”,他不但喜欢发贴,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子总数的一半。如果你有一个当前论坛上所有帖子(包括回帖)的列表,其中帖子作者的ID也在表中,你能快速找出这个传说中的Tango水王吗?
方法1:
先对ID进行排序,再遍历排序后的序列,统计每个ID的次数,从而寻找到最大次数的ID。
方法2:
假设ID列表已经是有序的,如果一个ID出现的次数超过总数的一半,那么,第N/2项一定回事这个ID;
方法3:
上面方法都要排序;
如果每次删除2个不同的ID,那么在剩下的ID列表中,ID 出现的次数仍然超过总数的一半;
所以可以不断重复这个过程;时间复杂度0(N),常数的额外内存;
1. 可以假设帖子的第一个ID是次数最大的,用candidate记录,次数用nTimes记录。
2. 遍历下一个ID,如果跟candidate一样,nTimes++,否则,遇到一个挑战,则nTimes--,
如果nTimes==0,下一步就要重复第一步了。
3.遍历结束,nTimes>0的那个candidate就是水王ID,他是获胜者。
#include<iostream> #include<stdio.h> using namespace std; typedef int Type; Type Find(Type* ID, int N) { Type candidate; int nTimes, i; for(i=nTimes=0;i<N;i++) { if(nTimes==0) { candidate=ID[i],nTimes=1; } else { if(candidate==ID[i]) nTimes++; else nTimes--; } } return candidate; } int main() { int a[]={1,2,3,3,1,1,1,1}; printf("%d\n",Find(a,8)); }
扩展问题:
随着Tango的发展,管理员发现,“超级水王”没有了。统计结果表明,有3个发帖很多的ID,
他们的发帖数目都超过了帖子总数目N的1/4。你能从发帖ID列表中快速找出他们的ID吗?
三个ID同时应战,但是这三个ID之间并不对战。所以问题很快得到解决。
#include<iostream> #include<stdio.h> using namespace std; typedef int Type; Type* Find(Type* ID,int N) { Type candidate[3]; Type ID_NULL;//定义一个不存在的ID int nTimes[3],i; nTimes[0]=nTimes[1]=nTimes[2]=0; candidate[0]=candidate[1]=candidate[2]=ID_NULL; for(i=0;i<N;i++) { if(ID[i]==candidate[0]) { nTimes[0]++; } else if(ID[i]==candidate[1]) { nTimes[1]++; } else if(ID[i]==candidate[2]) { nTimes[2]++; } else if(nTimes[0]==0) { nTimes[0]=1; candidate[0]=ID[i]; } else if(nTimes[1]==0) { nTimes[1]=1; candidate[1]=ID[i]; } else if(nTimes[2]==0) { nTimes[2]=1; candidate[2]=ID[i]; } else { nTimes[0]--; nTimes[1]--; nTimes[2]--; } } return candidate; } int main() { int a[]={8,8,3,4,5,4,4,8,3,3,8,3,3,4,8,4}; Type *r; r=Find(a,16); printf("%d,%d,%d\n",r[0],r[1],r[2]); }