数组中出现次数超过一半的数字

来源:互联网 发布:智能小车pid算法 编辑:程序博客网 时间:2024/05/17 03:13

若数组中出现次数超过数组长度一半的数字,请找出这个数字。

#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;}


0 0
原创粉丝点击