leetcode Majority Element II

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

摩尔投票法,如果不了解这个方法想自己想我觉得真是挺难的,关于摩尔投票法http://mabusyao.iteye.com/blog/2223195讲解的比较清楚,题目提示中问符合出现次数大于n/3的众数最多有几个,答案明显是2,那么我们用两个变量a,b作为候选众数,利用摩尔投票法找出可能的众数,再次遍历数组计算出现次数是否符合条件,代码:

public List<Integer> majorityElement(int[] nums) {
     List<Integer> list=new ArrayList<>();
    int a=0,b=0;
    int ca=0,cb=0;
    for(int num:nums){
        if(num==a){
            ca++;
        }
        else if(num==b){
            cb++;
        }
        else if(ca==0){
            a=num;
            ca=1;
        }
        else if(cb==0){
            b=num;
            cb=1;
        }
        else{
            ca--;
            cb--;
        }
    }
    ca=0;
    cb=0;
    for(int num:nums){
        if(a==num) ca++;
        else if(b==num) cb++;
    }
    int len=nums.length;
    if(ca>len/3) list.add(a);
    if(cb>len/3) list.add(b);
    return list;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值