zoj2132-The Most Frequent Number

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2132

The Most Frequent Number


Time Limit: 5 Seconds      Memory Limit: 1024 KB

Seven (actually six) problems may be somewhat few for a contest. But I am really unable to devise another problem related to Fantasy Game Series. So I make up an very easy problem as the closing problem for this contest.

Given a sequence of numbers A, for a number X if it has the most instances (elements of the same value as X) in A, then X is called one of the most frequent numbers of A. Now a sequence of numbers A of length L is given, and it is assumed that there is a number X which has more than L / 2 instances in A. Apparently X is the only one most frequent number of A. Could you find out X with a very limited memory?

Input

Input contains multiple test cases. Each test case there is one line, which starts with a number L (1 <= L <= 250000), followed by L numbers (-2^31 ~ 2^31-1). Adjacent numbers is separated by a blank space.

Output

There is one line for each test case, which is the only one most frequent number X.

Sample Input

5 2 1 2 3 2
8 3 3 4 4 4 4 3 4

Sample Output

2
4

思路:题意很简单,求一个数列里出现次数最多的那个数字,这个数字的个数是大于数列长度的1/2的。这里采用O(1)算法,利用大于1/2这个条件。

 #include <cstdio>

 int main()
{
int n,ans;
while(~scanf("%d",&n))
{
int m,cnt=;
for(int i=;i<n;i++)
{
scanf("%d",&m);
if(cnt==) ans=m,cnt++;
else if(ans==m) cnt++;
else cnt--;
}
printf("%d\n",ans);
}
return ;
}
上一篇:FZU Monthly-201901 tutorial


下一篇:VS Code 插件