给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。
Input
第1行一个正整数n。
第2行n个正整数用空格隔开。
Output
一行一个正整数表示那个众数。
Sample Input
5
3 2 3 1 3
Sample Output
3
这题有点意思,内存限制只有1M,网上普遍都是这种方法
#include<cstdio>
using namespace std;
int main()
{
int k=0, ans=0, n, a;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a);
if (a == ans)
k++;
else
{
k--;
if (k <= 0)
{k=1;ans = a; }
}
}
printf("%d",ans);
return 0;
}