Leetcode 之 Major 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.

和之前Major Element I很像,但是I中没有要求O(1)的空间,所以无法用HashMap 保存每个element 的status;

看了很多博主的文章才知道怎么做: 用摩尔投票法

先给出Major Element I的摩尔投票法的解法:
由与一个数组中次数大于1/2的数字只可能有一个,所以就用一个m保存majority element的candidate,用cm保存其出现次数,遍历数组的时候,如果遇到与此candidate不同的数,就在cm中抵消一次,如果相同,就在cm中加上一。这样就相当于把数组中两两不同的数一对一对地消除,最后剩下的就可能是真正的candidate。然后再遍历一遍数组,统计此candidate的次数,如果次数大于threshhold,就返回,否则,则不存在。

与之解法相同,以下是II的解法代码:

import java.util.*;

public class MajorEle {
    public List<Integer> majorityElement(int[] nums) {
        List <Integer>majorList=new ArrayList<Integer>();
        int threshhold=(int)(Math.ceil(nums.length/3));
        int m=0,n=0,cn=0,cm=0;
        for(int num:nums){
            if(n==num)cn++;
            else if(m==num)cm++;
            else if(cn==0){
                n=num;
                cn++;
            }
            else if(cm==0){
                m=num;
                cm++;
            }
            else {
                cn--;
                cm--;
            }

        }
        if(cn!=0){
            cn=0;
            for(int num:nums){
                if(num==n)cn++;
            }
            if(cn>threshhold)
                majorList.add(n);
        }
        if(cm!=0){
            cm=0;
            for(int num:nums){
                if(num==m)cm++;
            }
            if(cm>threshhold)
                majorList.add(m);
        }
        return majorList;
    }
    public static void main(String []args){
        MajorEle c=new MajorEle();
        int []nums={2,2,1,3};
        for(int n:c.majorityElement(nums))
            System.out.println(n);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值