Ignatius and the Princess IV (dp)

传送门:https://vjudge.net/problem/HDU-1029

题目:给一列数,找出出现(n+1)/2次的数字:

我们可以设一个标志,通过输入更新标志,来实现;如果输入的数和前边的数不同,就time--,否则,time++;如果time<=0了,我们就更新标志。因为他给的奇数,所以总有一个数会出现会多一次,所以不用担心会出现别的情况。

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    int n;
    int m;
    int c;
    while(cin>>n)
    {
        int time=0;
        while(n--)
        {
            cin>>m;
            if(time<=0)
                c=m;
            m==c?++time:--time;
        }
        cout<<c<<endl;
    }
    return 0;
}

思路启发来自一片博客,现在找不到了,该题还可以给输入的数排序,第(n+1)/2个数就是要求的数。我还想着利用桶排序的思想,不过,数据范围太大,有点耗费内存。

猜你喜欢

转载自blog.csdn.net/guagua_de_xiaohai/article/details/81255172
今日推荐