We set two pointers number1 and number2 to record the most probably element of which the amount is over 1/3. Meanwhile, we have count1 to record the their amounts. Firsty, both pointers point to nums[0]. And their amounts set to be zero. We use a for loop to traverse the array. When we find a element same as number1, we add the count1 by 1. In the same way, if we find an element same as number2, add count2 by 1. Otherwise, we decrease the count by 1, which means the possibility of current candidate decreases. If count1 decreases to zero, that means the previous elements we've scaned is unlikely be the suspect element we want to find. Thus we choose the current element to be the new candidate and set the correspondent count to be 1. Now we again traverse the array from the start to the end, if we find element same as the correspondent candidate, we add its amount. If the amount is beyond 1/3. That means we successfully find a targert, add it into the list.

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> resultList = new ArrayList<>();
        int len = nums.length;
        if(len == 0) return resultList;
        int number1 = nums[0], number2 = nums[0], count1 = 0, count2 = 0;
        for(int i = 0; i < len; i++){
            if(nums[i] == number1) count1++;
            else if(nums[i] == number2) count2++;
            else if(count1 == 0){
                number1 = nums[i];
                count1 = 1;
            }
            else if(count2 == 0){
                number2 = nums[i];
                count2 = 1;
            }
            else{
                count1--;
                count2--;
            }
        }
        count1 = 0;
        count2 = 0;
        for(int i = 0; i < len; i++){
            if(nums[i] == number1) count1++;
            else if(nums[i] == number2) count2++;
        }
        if(count1 > len/3) resultList.add(number1);
        if(count2 > len/3) resultList.add(number2);
        return resultList;
    }
}

 

posted on 2016-06-09 04:11  爱推理的骑士  阅读(120)  评论(0编辑  收藏  举报