229. Majority Element II(unsolved)

本文介绍了一种线性时间和O(1)空间复杂度的算法来找出数组中出现次数超过n/3的元素。该算法通过迭代数组并使用计数方式找到可能的候选者,再验证这些候选是否确实满足条件。

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

解答:
其实就是求众数,可以推测出,大于三分之一的众数是顶多只有两个的。那么遇见一个数就加一,遇见不是的就减一。假如减到零,就置为一。最后还要判断一下这个众数满不满足条件。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值