检查数组中超过一半的数的第二种解法

    xiaoxiao2021-03-25  71

    到第一个数时,让次数为1,每次遇到相同的数,次数加一,遇到不同的次数减去1;当次数为0时,让次数为1;那么数组中超过一半的肯定为最后一次次数为1时对应的

    那个数字,代码实现如下:

    int MoreThanHalfNum1(int* numbers,int length){

    if(CheckInvalidInput(numbers,length)){ return 0; } int times=1; int result=numbers[0]; for(int i=1;i<length;i++){ if(times=0){ result=numbers[i]; times=1; } else if(numbers[i]==result) times++; else times--; } if(!CheckMoreThanHalf(numbers,length,result)){ result=0; } return result; }//检查数组中超过一半的数的第二种解法
    转载请注明原文地址: https://ju.6miu.com/read-33131.html

    最新回复(0)