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

题目:数组中有一个数组出现的次数超过了数组长度的一半,找出这个数字。

答:

#include "stdafx.h"
#include <iostream>

using namespace std;

//查找数组中超过出现次数超过一半的数字
int FindNumber(int arr[], int length)
{
    if (NULL == arr || length <= 0)
    {
        return -1;
    }
    int nValue = arr[0];
    int count = 1;
    for (int i = 1; i < length; i++)
    {
        if (nValue == arr[i])
        {
            count++;
        }
        else
        {
            if (count == 0)
            {
                nValue = arr[i];
                count = 1;
            }
            count--;
        }
    }
    return nValue;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int arr[] = {1, 2, 3, 4, 5, 2, 2, 2, 2, 3, 2};
    cout<<FindNumber(arr, sizeof(arr)/sizeof(arr[0]))<<endl;
    return 0;
}

运行界面如下:

原文地址:https://www.cnblogs.com/venow/p/2659233.html