leetcode 169. Majority Element | 摩尔投票法

这篇博客介绍了如何使用摩尔投票法解决LeetCode第169题——寻找数组中的多数元素。摩尔投票法能高效地找到出现次数超过n/2的元素,且适用于找出数量大于n/3的情况。博主分享了从朴素计数法到摩尔投票法的思考过程,并提供了相关代码实现。

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

Description

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.

My solution

朴素的思想就是对每个值计数, 但这样实际上不止找到了majority, 其他的都找到了, 复杂度较高(因为做了无用功). 思考未果, 参考discuss

Discuss

其中一种较好的方案是采用摩尔投票法, 相同的思路, 还可以解决找出cnt > n/3 等概率的问题. 直接看代码
下面代码是记录index, 看起来不是很直观, 参见下方自己重写代码.

int majorityElement(vector<int> &num) {
    int majorityIndex = 0;
    for (int count = 1, i = 1; i < num.size(); i++) {
        num[majorityIndex] == num[i] ? count++ : count--;
        if (count == 0) {
            majorityIndex = i;
            count = 1;
        }
    }

    return num[majorityIndex];
}
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        // 参照discuss,采用摩尔投票法
        // 注意摩尔法还可以解决n/3...等概率问题
        int res = nums[0];
        int cnt=0;
        for(int i=0;i<nums.size();i++){
            if(cnt==0){
                res = nums[i];
                cnt++;
            }else{
                if(nums[i]!=res) cnt--;
                else cnt++;
            }
        }
        return res;
    }
};

总之, 摩尔投票法的基本思路就是找出两个不同的vote, 剔除掉, 最后剩下的一定是多数票.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值