Lintcode算法题:主元素 II

描述

给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。

补充:数组中只有唯一的主元素

样例

给出数组[1,2,1,2,1,3,3] 返回 1

挑战

要求时间复杂度为O(n),空间复杂度为O(1)。

解题:

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: The majority number that occurs more than 1/3
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        int candidate1 = 0, candidate2 = 0;
        int count1, count2;
        count1 = count2 = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (candidate1 == nums.get(i)) {
                count1 ++;
            } else if (candidate2 == nums.get(i)) {
                count2 ++;
            } else if (count1 == 0) {
                candidate1 = nums.get(i);
                count1 = 1;
            } else if (count2 == 0) {
                candidate2 = nums.get(i);
                count2 = 1;
            } else {
                count1--;
                count2--;
            }
        }
        count1 = count2 = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums.get(i) == candidate1) {
                count1++;
            } else if (nums.get(i) == candidate2) {
                count2++;
            }
        }    
        return count1 > count2 ? candidate1 : candidate2;
    }
}

 

posted @ 2019-01-25 20:42  yorkmass  阅读(178)  评论(0)    收藏  举报