[leetCode]Majority Element

本文介绍了两种方法来解决数组中找到出现次数超过一半的元素的问题。第一种方法通过使用哈希表统计每个元素的出现次数;第二种方法利用多数元素占总元素数量一半以上的特性进行优化。

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

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

题意:返回数组中出现次数最多的元素,该元素出现次数保证多余元素个数的一半。

思路:
方法1:普通的做法是分别统计每个元素出现的次数,然后找出出现次数最多的那个元素返回。这种方法比较繁琐,适用范围比较广。也是我想到的

方法2:抓住出现次数最多的那个元素占总的元素个数的一半还多,这个特点。这种方法最快,在该情况下最好。

//方法1
int majorityElement(std::vector<int>& nums) {

    std::map<int,int> numsTimes;

    //!< 将元素插入map,并计算出现次数
    std::vector<int>::const_iterator nums_it = nums.begin();
    while (nums_it != nums.end()) 
    {
        std::pair<std::map<int,int>::iterator, bool> ret = 
            numsTimes.insert(std::make_pair(*nums_it, 1));

        if (!ret.second)
        {
            ++ret.first->second;
        }

        ++nums_it;
    }

    //!< 查找出现次数多余一半的那个元素
    int halfNum = nums.size() >> 1;
    std::map<int,int>::const_iterator numsTimes_it =    numsTimes.begin();
    while (numsTimes_it != numsTimes.end())
    {
        if (numsTimes_it->second > halfNum)
        {
            return numsTimes_it->first;
        }

        ++numsTimes_it;
    }

    return 0;
}
 //方法2
 int majorityElement(std::vector& nums) { 

    int majorElement = nums[0]; 
    int count = 1;

    for( int i = 1; i < nums.size(); i++){
        if( nums[i] == majorElement)
            count++;
        else if( nums[i] != majorElement && count > 0)
            count--;
        else{
            majorElement = nums[i];
            count = 1;
        }
    }

    return majorElement;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值