[leetcode] 229. Majority Element II

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

分析

题目的意思是:找出一个数组中数字的频率大于1/3的数字。

  • 让我们先考虑可能会有多少个众数,经过举了很多例子分析得出,任意一个数组出现次数大于n/3的众数最多有两个。那么有了这个信息,我们使用投票法的核心是找出两个候选众数进行投票,需要两遍遍历,第一遍历找出两个候选众数,第二遍遍历重新投票验证这两个候选众数是否为众数即可,选候选众数方法和前面那篇Majority Element 求众数一样,由于之前那题题目中限定了一定会有众数存在,故而省略了验证候选众数的步骤,这道题却没有这种限定,即满足要求的众数可能不存在,所以要有验证。

代码

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> res;
        int m=0;
        int n=0;
        int cm=0;
        int cn=0;
        for(auto a:nums){
            if(a==m){
                cm++;
            }else if(a==n){
                cn++;
            }else if(cm==0){
                m=a;
                cm=1;
            }else if(cn==0){
                n=a;
                cn=1;
            }else{
                cm--;
                cn--;
            }
        }
        cm=0;
        cn=0;
        for(auto a:nums){
            if(a==m) cm++;
            else if(a==n) cn++;
        }
        if(cm>nums.size()/3) res.push_back(m);
        if(cn>nums.size()/3) res.push_back(n);
        return res;
    }
};

参考文献

[LeetCode] Majority Element II 求众数之二

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值