`

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 Element的变形,这里要求找出出现次数多余n/3次。我们通过分析可以知道这样的元素可能有两个,我们同样可以采用Moore算法,与上一题目不同的的是三个元素一组,这样在线性的时间复杂度下可以解决。代码如下:
public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> list = new ArrayList<Integer>();
        int result1 = 0;
        int result2 = 0;
        int count1 = 0, count2 = 0;
        for(int i : nums) {
            if(count1 == 0 && i != result2) {
                result1 = i;
            } else if(count2 == 0 && i != result1) {
                result2 = i;
            }
            if(i == result1) {
                count1 ++;
            } else if(i == result2) {
                count2 ++;
            } else {
                count1 --;
                count2 --;
            }
        }
        count1 = 0;
        count2 = 0;
        for(int i : nums) {
            if(i == result1) 
                count1 ++;
            else if(i == result2) 
                count2 ++;
        }
        if(count1 > nums.length / 3) list.add(result1);
        if(count2 > nums.length / 3) list.add(result2);
        return list;
    }
}
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics