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

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

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值