Ignatius and the Princess IV 

先搬中文

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 Descriptions:   给你n个数字,你需要找出出现至少(n+1)/2次的数字 现在需要你找出这个数字是多少? Input

本题包含多组数据,请处理到EOF: 每组数据包含两行。 第一行一个数字N(1<=N<=999999) ,保证N为奇数。 第二行为N个用空格隔开的整数。

Output

对于每组数据,输出一行,表示要求找到的那个数

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

题目链接:

https://vjudge.net/problem/HDU-1029

找出数列里面出现次数多于n/2的的元素

既然次数大于n/2,那么例如3、2、3、1、3、2、3

  1. 去掉3    2
  2. 去掉3    2
  3. 去掉3    1
  4. 还剩一个3

由此可得我们按照序列一次扫描,把第一个数字x赋值给ans,计数器cnt=0

若是后来数字x与ans相同,则cnt++,否则cnt-- 若cnt为0,则重新找(不用倒回开头)以此循即可

AC代码

 

#include <bits/stdc++.h>
#define Mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define MEM(x, y) memset(x, y, sizeof(x))
#define Maxn 1000
using namespace std;
int main()
{
    int n,x,ans,cnt;
    while(cin>>n)
    {
        cnt=0;
        for(int i=0; i<n; i++)//存数
        {
            cin>>x;
            if(cnt==0)//计数器为0,重新计数
            {
                ans=x;
                cnt=1;
            }
            else
            {
                if(ans==x)//相同,计数器+1
                    cnt++;
                else//不同-1
                    cnt--;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

 

 

 

 

 

   
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄