题目:数组中有一个数字出现的次数超过了数组长度的一半,找出这个数字。
bool g_bInputInvalid = false;//输入的数组是否合法
int MoreThanHalfNum(int * array ,unsigned int length){
if(array == null && length <= 0){
g_bInputInvalid = true;
return 0;
}
g_bInputInvalid = false;
int result = array[0];
int times = 1;
for(int i=1; i<length; i++){
if(times == 0){
result = array[i];
times = 1;
}
}
else if(result == array[i]){
times ++
}
else{
times --
}
}
//检测是否满足大于一半
times = 0;
for(int i= 0;i<length;i++){
if(result == array[i]){
times++;
}
}
if(times*2 < length){
g_bInputInvalid = true;
result = 0;
}
return result;
}
681

被折叠的 条评论
为什么被折叠?



