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

Hint:

  1. How many majority elements could it possibly have?
思路分析:这题是Majority Element的扩展,相同能够採用Moore投票法解决。首先须要分析,假设这种元素(elements that appear more than ⌊ n/3 ⌋ times)存在,那么一定不会超过两个,证明用反证法非常easy理解。接下来就是怎样找出这可能的两个元素。能够分两步,找两个candidate和验证candidate出现的次数是否超过⌊ n/3 ⌋ times。 找两个候选candidate的方法就是Moore投票法,和Majority Element中相似。须要验证的原因是,不同于Majority Element中已经限制了主元素一定存在。这题不一定存在这种元素。即使存在个数也不确定,所以须要验证过程。时间复杂度O(n),空间复杂度O(1).
AC Code:
public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        //moore voting
        //0632
        int candidate1 = 0, candidate2 = 0, times1 = 0, times2 = 0;
        int n = nums.length;
        for(int i = 0; i < n; i++){
            if(nums[i] == candidate1) {
                times1++;
            } else if(nums[i] == candidate2){
                times2++;
            } else if(times1 == 0) {
                candidate1 = nums[i];
                times1 = 1;
            } else if(times2 == 0){
                candidate2 = nums[i];
                times2 = 1;
            } else{
                times1--;times2--;
            }
        }
        
        times1 = 0; times2 = 0;
        for(int i = 0; i < n; i++){
            if(nums[i] == candidate1) times1++;
            else if(nums[i] == candidate2) times2++;
        }
        
        List<Integer> res = new ArrayList<Integer>();
        if(times1 > n/3) {
            res.add(candidate1);
        }
        if(times2 > n/3) {
            res.add(candidate2);
        }
        return res;
        //0649
    }
}


posted @ 2017-04-20 19:16  jzdwajue  阅读(75)  评论(0编辑  收藏  举报