2456: mode
Time Limit: 1 Sec Memory Limit: 1 MB
Submit: 7146 Solved: 2809
[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
借鉴:https://www.cnblogs.com/MashiroSky/p/5916163.html
#include <cstdio>
int main() //某个数一定存在> n div 2的情况
{ //也就是众数比其他数的和还要多,
//利用替换的思想,众数一定会保留下来
int n;
scanf("%d",&n);
int x=0,y=1,c;
for(int i=1;i<=n;i++)
{
scanf("%d",&c);
if(c==x)
y++;
else
y--;
if(y<=1) //y==0就是抵消替换的标志
x=c,y=1;
}
printf("%d",x);
return 0;
}