*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.

 

解题思路:

Majority Elements不同是这里需要维护两个变量n1和n2,如果下一个数与这两个数都不同的时候,count1和count2都减一,如果下一个数与n1或者n2相等的时候,对应的count++。最后的结果必定在n1或者n2中。

The basic idea is based on Moore's Voting Algorithm, we need two candidates with top 2 frequency. If meeting different number from the candidate, then decrease 1 from its count, or increase 1 on the opposite condition. Once count equals 0, then switch the candidate to the current number. The trick is that we need to count again for the two candidates after the first loop. Finally, output the numbers appearing more than n/3 times.

 

public class Solution{
    public List<Integer> majorityElement(int[] nums){
        List<Integer> rst = new ArrayList<Integer>();
        if(nums == null || nums.length == 0) return rst;
        int count1 = 0, count2 = 0, candidate1 = 0, candidate2 = 1;
        for(int num : nums){
            if(num == candidate1) count1++;
            else if(num == candidate2) count2++;
            else if(count1 == 0){
                candidate1 = num;
                count1 = 1;
            }
            else if(count2 == 0){
                candidate2 = num;
                count2 = 1;
            }
            else{
                count1--;
                count2--;
            }
        }
        count1 = 0; count2 = 0;
        for(int num : nums){
            if(num == candidate1) count1+=1;
            else if(num == candidate2) count2 +=1;
        }
        if (count1 > nums.length/3 ) rst.add(candidate1);
        if (count2 > nums.length/3 ) rst.add(candidate2);
        return rst;
    }
}

 

https://leetcode.com/discuss/69126/concise-java-solution-based-on-moores-voting-algorithm

posted @ 2015-07-14 15:36  Hygeia  阅读(154)  评论(0编辑  收藏  举报