229. Majority Element II

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]

难度:medium

题目:给定一整数数组,找出其元素出现次数大于其三分之一长度的所有元素。
注意:算法时间复杂度O(n),空间复杂度为O(1)

思路:投票法。
1 找出三个不同的候选人,各消除一票,如果票数为0 退出候选人队列。
2 最后对剩下的候选人重新统计票数

Runtime: 2 ms, faster than 97.44% of Java online submissions for Majority Element II.
Memory Usage: 39.8 MB, less than 29.68% of Java online submissions for Majority Element II.

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> result = new ArrayList<>();
        if (null == nums) {
            return result;
        }
        
        int[] elems = new int[2];
        int[] count = new int[2];
        for (int i = 0; i < nums.length; i++) {
            if (elems[0] == nums[i]) {
                count[0]++;
            } else if (elems[1] == nums[i]) {
                count[1]++;
            } else {
                if (count[0] > 0 && count[1] > 0) {
                    count[0]--;
                    count[1]--;
                } else if (0 == count[0]) {
                    elems[0] = nums[i];
                    count[0] = 1;
                } else if (0 == count[1]) {
                    elems[1] = nums[i];
                    count[1] = 1;
                }
            }
        }
        int c0 = 0, c1 = 0;
        for (int i = 0; i < nums.length; i++) {
            if (count[0] > 0 && nums[i] == elems[0]) {
                c0++;
            }
            if (count[1] > 0 && nums[i] == elems[1]) {
                c1++;
            }
        }
        
        if (c0 > nums.length / 3) {
            result.add(elems[0]);
        }
        
        if (c1 > nums.length / 3) {
            result.add(elems[1]);
        }
        
        return result;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018325444
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞