若数组中出现次数超过数组长度一半的数字,请找出这个数字。
#include <iostream>
#include <algorithm>
using namespace std;
//检查输入的数组是否有效
bool checkArray(int *a,int len){
if( a==NULL || len<=0){
return false;
}
return true;
}
//检查数组中的某个数字出现次数是否超过数组长度的一半
bool checkMoreThanHalf(int *a,int len,int num){
int count=0;
for(int i=0;i<len;i++){
if(num==a[i]){
count++;
}
}
if(count*2>=len){
return true;
}
return false;
}
//首先想到的当然是排序
int BySort(int *a,int len){
if(!checkArray(a,len)) return 0;
sort(a,a+9);
int res=a[len/2];
if(!checkMoreThanHalf(a,len,res)) return 0;
return res;
}
//根据数组特点的方法
int MoreThanHalfNum(int *a,int len){
if(!checkArray(a,len)){
return 0;
}
int res=a[0];
int times=1;
for(int i=0;i<len;i++){
if(times==0){
res=a[i];
times++;
}
else if(res==a[i]){
times++;
}
else{
times--;
}
}
if(!checkMoreThanHalf(a,len,res)) return 0;
return res;
}
int main(){
int a[9]={1,2,3,2,2,2,5,4,2};
//cout<<"The number of "<<MoreThanHalfNum(a,9)<<" is more than half"<<endl;
cout<<"The number of "<<BySort(a,9)<<" is more than half"<<endl;
return 0;
}
原文地址:http://blog.csdn.net/dutsoft/article/details/26684557