[jobdu]数组中出现次数超过一半的数字

找到以后要再扫一遍确认。

http://zhedahht.blog.163.com/blog/static/25411174201085114733349/

#include <iostream>
#include <memory.h>
#define LEN 100005
#define ulong unsigned long long
using namespace std;

ulong A[LEN];

int main()
{
    int n;
    while (cin >> n)
    {
        for (int i = 0; i < n; i++)
        {
            cin >> A[i];
        }
        int count = 0;
        ulong candidate = 0;
        for (int i = 0; i < n; i++)
        {
            if (count == 0)
            {
                count++;
                candidate = A[i];
            }
            else if (candidate == A[i])
            {
                count++;
            }
            else
            {
                count--;
            }
        }
        count = 0;
        for (int i = 0; i < n; i++)
        {
            if (A[i] == candidate) count++;
        }
        if (count * 2 > n)
        {
            cout << candidate << endl;
        }
        else
        {
            cout << -1 << endl;
        }
    }
    return 0;
}

  

posted @ 2013-11-02 20:26  阿牧遥  阅读(229)  评论(0)    收藏  举报