【每日一题】数组中出现次数超过一半的数字

题目来源
牛客网
链接:数组中出现次数超过一半的数字

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

输入:

[1,2,3,2,2,2,5,4,2]

输出:

2

解题思路
记录数组中每个数字出现的次数count,若次数超过一半,返回该数字;若未超过一半,将count置为1,从新计数。

代码展示

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

猜你喜欢

转载自blog.csdn.net/zhao_leilei/article/details/110231502