Description
给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。
Input
第1行一个正整数n。
第2行n个正整数用空格隔开。
Output
一行一个正整数表示那个众数。
Sample Input
5
3 2 3 1 3
Sample Output
3
空间只有1MB,很重要。
所以我们不能开数组。
怎么算呢?我们可以利用数字出现次数很多的优势。我们采用数字抵消的思想。记录当前数字的次数,如果数字相等就直接次数加一,不然减一。
AC代码:
#include<stdio.h>
//#define int long long
using namespace std;
int n,cnt,res;
signed main(){
scanf("%d",&n);
for(int i=1,x;i<=n;i++){
scanf("%d",&x);
if(!cnt) cnt=1,res=x;
else if(x==res) cnt++;
else cnt--;
}
printf("%d\n",res);
return 0;
}