Majority Element II--多数投票算法(Majority Vote Alogrithm)

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
Solution:
1、Count and sort, O(n) space.
2、Using Majority Vote Alogrithm.
class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> l = new LinkedList<Integer>();
        if (nums == null || nums.length == 0) return l;
        int n1 = 0, n2 = 1; //make sure n1 is different from n2
        int c1 = 0, c2 = 0;
        for (int i : nums) {
            if (n1 == i) c1++;
            else if (n2 == i) c2++;
            else if (c1 == 0) {
                c1++;
                n1 = i;
            } else if (c2 == 0) {
                c2++;
                n2 = i;
            } else {
                c1--;
                c2--;
            }
        }
        int count1 = 0, count2 = 0;
        for (int i : nums) {
            if (i == n1) count1++;
            if (i == n2) count2++;
        }
        if (3*count1 > nums.length) l.add(n1); //count more than 1/3
        if (3*count2 > nums.length) l.add(n2);
        return l;
    }
}

 

posted @ 2018-07-13 17:31  lennyT  阅读(157)  评论(0)    收藏  举报