首页 > 其他 > 详细

1029:Ignatius and the Princess IV

时间:2016-11-27 14:09:45      阅读:167      评论:0      收藏:0      [点我收藏+]

题目大意是找出数组中出现次数超过一半的数。

基本思想:每遇到两个不同的数就消掉,设一个计数器就行了。

       存出现次数最大的那个数的出现次数。

     当下一个数与当前的数不同时,计数器减一,相同,则加一。

实现代码

技术分享
 1 #include <iostream>
 2 #include <stdio.h>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     int n,x,m_max,cnt;
 8  
 9  //   while(cin>>n)
10     while(scanf("%d",&n)!=EOF)
11     {
12 
13         cnt = 0;
14  //      while(n--)
15         for(int i = 0;i<n;i++)//相比之下,for的运行时间更少,所以能用for的,不要用while
16         {
17  //          cin>>x;
18             scanf("%d",&x);
19            if(!cnt)
20            {
21                m_max = x;
22                cnt++;
23            }
24            else if(x!=m_max) cnt--;
25            else if(x==m_max) cnt++;
26          }
27  //        cout<<m_max<<endl;
28         printf("%d\n",m_max);
29     }
30     return 0;
31 }
View Code

 

1029:Ignatius and the Princess IV

原文:http://www.cnblogs.com/ttzm/p/6106275.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!