BZOJ2456 mode 【众数】

BZOJ2456: mode

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。

题解:

由于内存不足,被迫解锁了一种新的求众数的方法:抵消法,复杂度 n 。

由于众数的个数 >= n div 2,所以我们把两个不同的数抵消,不同的数叠加,最后剩下的一定是众数(学到了

二话不说上代码:

 1 #include<cstdio>
 2 int n,x,y,num;
 3 int main()
 4 {
 5     scanf("%d",&n);
 6     while (n--)
 7     {
 8         scanf("%d",&y);
 9         if (!num) num++,x=y;
10         else {
11             if (y!=x) num--;
12             else num++;
13         }
14     }
15     printf("%d",x);
16 }
View Code

加油加油加油!!! fighting fighting fighting !!!

猜你喜欢

转载自www.cnblogs.com/Frank-King/p/9223485.html