Time Limit: 1 Sec Memory Limit: 1 MB
Submit: 2819 Solved: 1190
[Submit][Status][Discuss]
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。
zju2132 The Most Frequent Number
Source
鸣谢 黄祎程
抵消思想
#include<cstdio>
inline int in(int x=0,char ch=getchar()){while(ch>'9'||ch<'0') ch=getchar();
while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();return x;}
int ans,x,n,m,tms;
int main(){
n=in();m=n/2+1,ans=in(),tms=1;
for(int i=1;i<n&&tms<m;i++){
x=in();
if(x==ans) tms++;else if(tms>1) tms--;else ans=x;
}
printf("%d\n",ans);
return 0;
}