题目:找到数组中个数大于总数一半的数字,比如 1,7,4,2,4,2,6,2,2,2,2,2,2,2
分析:大于一半就是比其他的个数总和还多,设置一个变量now保存当前值,一个变量保存now的次数count,遍历数组,如何和当前值一样,count+1,如果不一样-1,如果count=0了,改变now值为arr[i]count 置1
int MoreThanHalf(int arr[],int length)
{
if (length<=0 || arr==NULL) {
return 0;
}
int count=0;
int now=arr[0];
for (int i=0; i<length; i++) {
if (arr[i]==now) {
count++;
}
else{
count--;
if (count<0) {
now=arr[i];
count=1;
}
}
}
return now;
}