`

Leetcode - Majority Element II

 
阅读更多
[分析] Majority Element II这个扩展版可以沿用Majority Element 中的Moore Voting解法,大于 N / 3最多有两个,遍历过程中记录两个候选值。需注意的是,遍历结束后的候选值并不一定符合条件,比如input= [1,1,2],因此需要个检查过程。
[ref]
对Moore Voting算法解析
http://blog.csdn.net/joylnwang/article/details/7081575

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        // Moore voting
        List<Integer> result = new ArrayList<Integer>();
        if (nums == null || nums.length == 0) return result;
        int N = nums.length;
        int cand1 = nums[0], counter1 = 1;
        int i = 1;
        while (i < N && cand1 == nums[i]) {
            counter1++;
            i++;
        }
        if (i == N) {
            result.add(cand1);
            return result;
        }
        int cand2 = nums[i++], counter2 = 1;
        while (i < N) {
            if (nums[i] == cand1) {
                cand1 = nums[i];
                counter1++;
            } else if (nums[i] == cand2) {
                cand2 = nums[i];
                counter2++;
            } else {
                if (counter1 == 0) {
                    cand1 = nums[i];
                    counter1++;
                } else if (counter2 == 0) {
                    cand2 = nums[i];
                    counter2++;
                } else {
                    counter1--;
                    counter2--;
                }
            }
            i++;
        }
        // check cand1 & cand2
        int c1 = 0, c2 = 0;
        for (int j = 0; j < N; j++) {
            if (cand1 == nums[j])
                c1++;
            else if (cand2 == nums[j])
                c2++;
        }
        if (c1 > N / 3) 
            result.add(cand1);
        if (c2 > N / 3) 
            result.add(cand2);
        return result;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics