码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-05-24 14:25:42      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:数据结构   算法   

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

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


数组中出现次数超过一半的数字,布布扣,bubuko.com

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

标签:数据结构   算法   

原文地址:http://blog.csdn.net/dutsoft/article/details/26684557

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!