10-22每日一题:Leetcode229. 求众数 II

Leetcode229. 求众数 II

思路一:哈希

使用哈希表记录每一个数出现的次数,因为数据范围很大不能使用数字模拟(可以使用离散化的方式),最后再遍历一遍哈希表(顺便达到去重的目的)

时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)
class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        unordered_map<int, int> hash;
        int n = nums.size();
        vector<int> res;
        for (auto& num : nums) {
            hash[num] ++ ;
        }
        for (auto [u, cnt] : hash)
            if (cnt > n / 3) res.push_back(u);
        return res;
    }
};

思路二:摩尔投票法

我们知道在,求出现次数超过一半的数的时候,使用一个变量记录可能的投票结果,那么本题变量最多不会超过 k − 1 k-1 k1个,我们使用两个变量分别记录投票的结果,最后再遍历一遍判断是否出现的次数超过 1 / 3 1/3 1/3,保留出现次数超过 1 / 3 1/3 1/3的变量

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        int a = 0x3f3f3f, b = 0x3f3f3f;
        int c1 = 0, c2 = 0;
        for (auto& num : nums) {
            if (num == a) c1 ++ ;
            else if (num == b) c2 ++ ;
            else if (c1 == 0) a = num, c1 ++ ;
            else if (c2 == 0) b = num, c2 ++ ;
            else {
                c1 -- ;
                c2 -- ;
            }
        }
        c1 = 0, c2 = 0;
        for (auto &num : nums) {
            if (num == a) c1 ++ ;
            if (num == b) c2 ++ ;
        }
        vector<int> res;
        int n = nums.size();
        if (c1 > n / 3) res.push_back(a);
        if (c2 > n / 3) res.push_back(b);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Shirandexiaowo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值