《剑指offer》28数组中出现次数超过一半的数字

题目描述

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

解法:对数组中的每一项进行计数统计,输出超过一半个数的项。

代码如下:

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
    int num=numbers.size();
    if(num==0){
        return 0;
    }
    map<int,int> numcount;
    for(int i=0;i<num;i++){
        numcount[numbers[i]]++;
    }
    for(int i=0;i<num;i++){
        if(numcount[numbers[i]]>num/2){
            return numbers[i];
        }
    }
    return 0;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42056625/article/details/88240892