HDU1029 Ignatius and the Princess IV (O(n)级别的解法)

题意

给你n个数字,你需要找出出现至少(n+1)/2次的数字 现在需要你找出这个数字是多少?

解题

用b[i]表示i出现的次数。
遍历一遍数组a,统计每个值出现的次数。最后输出出现次数符合要求的值。

AC代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int maxn=1e6+7;
int a[maxn],b[maxn];
int main()
{
    int n,ans=-1;
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        memset(b,0,sizeof(a));
        for(int i=0;i<n;i++)
            b[a[i]]++;
        for(int i=0;i<n;i++)
            if(b[a[i]]>=(n+1)/2)
        {
            ans=a[i];
            break;
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37685156/article/details/81137291