BZOJ2456

2456: 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。

【题解】

1MB= =

(卡空间题见多了= =,没卡空间不就是一道LOW题= =)

由于卡空间,不能使用Hash和排序算法

但是众数一定大于总数的一半(咦)

那么这样统计 

如果这个数和之前假设的众数相同,那么该众数个数+1

否则由于该数可能不是众数,个数-1

如果众数个数为0,说明该众数个数在之前的序列中不足一半。同时更新众数。

将所有序列的处理完最后保存的众数就是答案

 1 #include<stdio.h>
 2 int a,b,n;
 3 void init()
 4 {
 5     scanf("%d",&n);
 6     while(n--)
 7     {
 8         int c;
 9         scanf("%d",&c);
10         if(a==0)
11         {a++;b=c;}
12         else
13         {
14             if(b==c)
15             a++;
16             else
17             a--;
18         }
19     }
20     printf("%d
",b);
21 }
22 int main()
23 {
24     init();
25     return 0;
26 }
原文地址:https://www.cnblogs.com/diamonddd/p/4611594.html