Description
给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。
Input
第1行一个正整数n。
第2行n个正整数用空格隔开。
Output
一行一个正整数表示那个众数。
Sample Input
5
3 2 3 1 3
Sample Output
3
HINT
100%的数据,n<=500000,数列中每个数<=maxlongint。
题解
1M内存找众数。
因为是找出现次数>n/2而非>=n/2,因此我们可以每次找两个不同的数消掉,剩下的数就是众数。
#include <cstdio>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
int ss=0,sn=0;
for(int i=1;i<=n/2;i++)
{
int t1,t2;
scanf("%d%d",&t1,&t2);
if(t1==t2)
{
if(!ss)
{
ss=t1,sn=2;
}
else if(ss==t1)
{
sn+=2;
}
else
{
sn-=2;
if(!sn)ss=0;
}
}
}
if(n%2)
{
int t;
scanf("%d",&t);
if(!ss||ss==t)
{
printf("%d",t);
}
else
{
printf("%d",ss);
}
}
else
{
printf("%d",ss);
}
return 0;
}
本文介绍了一种使用有限内存查找数列中出现次数超过一半的众数的算法。该算法通过对比并消除不同元素来逐步确定可能的众数,并提供了一个具体的C++实现示例。
2679

被折叠的 条评论
为什么被折叠?



