剑指offer39题-数组中出现次数超过数组长度一半的数

本文介绍了三种高效查找数组中出现次数超过一半的数字的方法:使用哈希表统计、排序法和摩尔投票法。其中,摩尔投票法是一种创新且高效的解决方案,特别适合大数据量的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2

限制:

1 <= 数组长度 <= 50000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

1.利用哈希表统计出现数字的次数

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int,int> hash;
        int res = 0, len = nums.size();
        for(int i = 0; i < len; i++){
            hash[nums[i]]++;
            
            if(hash[nums[i]] > len/2)
                res = nums[i];
        }
        return res;
    }
};

2.利用排序,超过一半的数字一定在数组的最中间

class Solution {
public:
    int majorityElement(vector<int>& nums) {
    sort(nums.begin(),nums.end());
    return nums[nums.size()/2];
    }
};

3.摩尔投票法,学习思路来自于 Leetcode Krahets大神

https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/mian-shi-ti-39-shu-zu-zhong-chu-xian-ci-shu-chao-3/

class Solution {
public:
    int majorityElement(vector<int>& nums) {
    //摩尔投票法 因为最多的数字一定多于数组内其他数字,所以遇到该数+1遇到不相等的数-1 当投票为0时,剩余数组内数字的众数也一定多与其他数字。
    int vote=0;//投票
    int res=0;
    for(int i=0;i<nums.size();i++)
    {
        if(vote==0)res=nums[i];
        //如果投票数为0 则设定当前数字为可能最多
        if(res!=nums[i])//如果当前数字不等于设定的数字
        {
            vote--;//投票--
        }else//如果相等则++
        {
            vote++;
        }
    }
    return res;
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值