HDU1029 Ignatius and the Princess IV 腾讯面试题抢红包(?)(模拟)

Problem Description
“OK, you are not too bad, em… But you can never pass the next test.” feng5166 says.

“I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers.” feng5166 says.

“But what is the characteristic of the special integer?” Ignatius asks.

“The integer will appear at least (N+1)/2 times. If you can’t find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha…..” feng5166 says.

Can you find the special integer for Ignatius?

Input
The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.

Output
For each test case, you have to output only one line which contains the special number you have found.

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

Author
Ignatius.L

Recommend
We have carefully selected several similar problems for you: 1074 1028 1203 1087 1114

今天算法课老师问了这个问题。据说是腾讯面试抢红包的那道题(至于是真的假的我就不知道了),题面大意是有一个人抢到了n个红包,告诉你每个红包的金额,且某个数额的红包被抢到了2/n次以上,让设计一个算法求出这个金额。
实际上和杭电的这题一模一样。。一个很简单的O(n)的算法,同时只需要用两个辅助变量即可完成,利用的就是出现2/n次以上这个性质,算法的核心是出现次数的抵消因为出现了2/n次以上,所以最后消完可以保证留下出现2/n次以上的那个数(最坏的情况也会比其他数字出现的次数多一次,所以会剩下)。cnt数组维护某个数字出现的次数,big用来维护最大的这个数字。具体看代码:

#include "cstring"
#include "cstdio"
#include "string.h"
#include "iostream"
using namespace std;
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int cnt,big;
        cnt=1;
        big=0;
        for(int i=1;i<=n;i++)
        {
            int temp;
            scanf("%d",&temp);
            if(temp!=big)
            {
                if(cnt==1)
                {
                    big=temp;
                    continue;
                }
                else
                {
                    cnt--;
                    continue;
                }
            }
            else
            cnt++;
        }
        printf("%d\n",big);
    }
}

你可能感兴趣的:(模拟)