/***********************************************************************
有个数字出现的次数超过了数组长度的一半,也就是,
有个数字出现的次数比其他所有数字出现次数的和还要多。
遍历数组时保存连个值,一个是数组中的数字,一个是出现的次数,
遍历到一个数字时,如果该数字和之前保存的数字相同,则次数加一,
如果该数字和之前保存的数字不同,则次数减一,如果次数为零,
遍历下一个数组元素,并把次数设为一。
要找的数字肯定是最后一次把次数设为1时对应的数字。
*************************************************************************/
#include<iostream>
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<<re;
}