II Boyer-Moore Majority Vote Algorithm

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

Note: code is from leetcode discuss forum.

public class Solution {  
    public List majorityElement(int[] nums) {  
        // 1, 2  
        List res = new ArrayList<>();  
        if(nums==null || nums.length==0) return res;  
        if(nums.length==1) {  
            res.add(nums[0]);  
            return res;  
        }  
          
        int m1 = nums[0];  
        int m2 = 0;  
          
        int c1 = 1;  
        int c2 = 0;  
          
        for(int i=1; inums.length/3) res.add(m1);  
        if(c2>nums.length/3) res.add(m2);  
        return res;  
    }  
}

你可能感兴趣的:(II Boyer-Moore Majority Vote Algorithm)