题目:
给你一个n个数的数列,其中某个数出现了超过n /2次即众数,请你找出那个数。
解法:
1.利用容器的话,会消耗很大的内存。
2.利用消耗法,由于超出一半的数是众数而且只有一个,那么可以在每次输入的时候进行自行消耗,那么到最后留下的那个就是最多的。
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
int main()
{
int n;
while (~scanf("%d", &n))
{
int count=0,pos=0;
while(n--)
{
int a;
scanf("%d",&a);
if(pos==a)
count++;
else//不相等,便消耗
{
count--;
if(count<=0)//说明它不是个数最多的数字
{
count=1;
pos=a;
}
}
}
printf("%d\n",pos);
}
return 0;
}