剑指offer第二十八题【数组中出现次数超过一半的数字】c++实现

来源:互联网 发布:o nonblock linux 编辑:程序博客网 时间:2024/05/16 18:25
数组中出现次数超过一半的数字
  • 参与人数:1910时间限制:1秒空间限制:32768K
  • 通过比例:20.40%
  • 最佳记录:0 ms|8552K(来自  牛客655987号)

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

设current为数组第一个元素count=1,遍历一遍数组,如果当前数值与current相同则count+1,否则count-1。查询最后的current,如果有超过一半的数字,那current一定等于那个数,但是current的数值不一定是结果,所以最后需要再验证一下。

int MoreThanHalfNum_Solution(vector<int> numbers) {    int length=numbers.size();    if(length==0){        return 0;    }    int current=numbers[0];    int counts=1;    for(int i=1;i<length;i++){        if(counts==0){            current=numbers[i];            counts=1;        }else{            if(current==numbers[i]){                counts++;            }else{                counts--;            }        }    }    counts=0;    for(int i=0;i<length;i++){        if(numbers[i]==current){            counts++;        }    }    if(counts>length/2){        return current;    }    return 0;}


0 0
原创粉丝点击