Ignatius and the Princess IV

区块链

577人已加入

描述

Ignatius and the Princess IV

describe
“OK, you are not too bad, em… But you can never pass the next test.” feng5166 says.

“I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers.” feng5166 says.

“But what is the characteristic of the special integer?” Ignatius asks.

“The integer will appear at least (N+1)/2 times. If you can’t find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha…..” feng5166 says.

Input
The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.

Output
For each test case, you have to output only one line which contains the special number you have found.

Sample Input

5 1 3 2 3 3 11 1 1 1 1 1 5 5 5 5 5 5 7 1 1 1 1 1 1 1

Sample Output

3 5 1

此题让求奇数个数中出现次数超过总数一半的数,容易超时超内存,这里使用一种比较简单的算法。首先要知道,在所有数中,去除两个不同的数对结果没有影响,利用这一点我们可以先记录第一次输入的数,如果和下一次输入的数相同,计数器加一,否则减一(即去除两个不同数);当计数器为零时,这个数被全部去除,然后再记录下一次输入的数,重复上述操作。当输入全部数之后,所留下的记录的数就是答案。

#include int main() { int n,t,res,cnt=0,i; while(scanf("%d",&n)!=EOF) { scanf("%d",&t); res=t; cnt=1; for(i=1;i"%d",&t); if(res==t) cnt++; else cnt--; if(cnt==0) { res=t; cnt=1; } } printf("%d\n",res); } return 0; }

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 相关推荐

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分