1029:Ignatius and the Princess IV

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

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

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

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

实现代码

 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
",m_max);
29     }
30     return 0;
31 }
View Code
原文地址:https://www.cnblogs.com/ttzm/p/6106275.html