Description
给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。
Input
第1行一个正整数n。
第2行n个正整数用空格隔开。
Output
一行一个正整数表示那个众数。
Sample Input
5
3 2 3 1 3
3 2 3 1 3
Sample Output
3
HINT
100%的数据,n<=500000,数列中每个数<=maxlongint。
因为众数要超过一半,所以我们让两个不相同的数相互抵消,最后剩下的就是众数了
1 #include<cstdio> 2 using namespace std; 3 int n,cnt,x,num; 4 int main() 5 { 6 scanf("%d",&n); 7 for (int i=1;i<=n;++i) 8 { 9 scanf("%d",&x); 10 if (cnt==0) 11 { 12 cnt++; 13 num=x; 14 } 15 else 16 if (x!=num) 17 cnt--; 18 else 19 cnt++; 20 } 21 printf("%d",num); 22 }