BZOJ2456: mode

2456: mode

Time Limit: 1 Sec  Memory Limit: 1 MB
Submit: 1301  Solved: 569
[Submit][Status]

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

题解:
神做法!把每个数和一个与它不同的数相抵消,由于要求的数出现了超过n div 2次,那么最后剩下的就是答案。
代码:
 1 var i,t,x,tot,n:longint;
 2 begin
 3   assign(input,'input.txt');assign(output,'output.txt');
 4   reset(input);rewrite(output);
 5   readln(n);read(x);t:=x;tot:=1;
 6   for i:=2 to n do
 7    begin
 8      read(x);
 9      if x=t then inc(tot)
10      else if tot=0 then begin t:=x;tot:=1;end
11      else dec(tot);
12    end;
13   writeln(t);
14   close(input);close(output);
15 end.      
View Code
原文地址:https://www.cnblogs.com/zyfzyf/p/3916780.html