【HDU - 1029】Ignatius and the Princess IV (水题)

Ignatius and the Princess IV c++

先搬中文spa

Descriptions:
 
给你n个数字,你须要找出出现至少(n+1)/2次的数字 如今须要你找出这个数字是多少?
Input

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

Outputcode

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

Sample Inputip

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 Outputci

3
5
1

题目连接:get

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

it

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

既然次数大于n/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;
}
相关文章
相关标签/搜索