面接:配列の1つの数字が配列の長さの半分を超えて現れ、この数を見つけます


/***********************************************************************
                   ,   ,
                         。
          ,         ,        ,
        ,               ,     ,
               ,     ,      ,
         ,       。
                 1      。
*************************************************************************/
#include
using namespace std;
 
int MoreThanHalfNum(int* numbers, unsigned int length)
{
    if(numbers == NULL && length == 0)
    {
         return -1;
    }
    
    int result = numbers[0];
    int times = 1;
    for(int i = 1; i < length; i++)
    {
        if(times==0)  //             0         ,        
        {
            result=numbers[i];
            times=1;  //      
        }
        else if(numbers[i] == result)
            times++;
        else
            times--;
    }
    // verify whether the input is valid
    times  = 0;
    for(i = 0;  i < length; ++i)
    {
        if(numbers[i] == result)
        times++;
    }
    if(times * 2 <= length)
    {
        
        result = -1;
    }
    return result;
}
int main()
{
    int a[]={1,2,2,3,4,5,2,2,2};
    int re=MoreThanHalfNum(a,9);
    cout<