229. Majority Element II

;  |     Back to Homepage   |     Back to Code List


class Solution {
    public List majorityElement(int[] nums) {
        int ele1 = 0, ele2 = 0;
        int vote1 = 0, vote2 = 0;
        for (int num : nums) {
            if (ele1 == num && vote1 > 0) {
                vote1 += 1;
            } else if (ele2 == num && vote2 > 0) {
                vote2 += 1;
            } else if (vote1 == 0) {
                vote1 = 1;
                ele1 = num;
            } else if (vote2 == 0) {
                vote2 = 1;
                ele2 = num;
            } else {
                vote1 -= 1;
                vote2 -= 1;
            }
        }
        int cnt1 = 0, cnt2 = 0;
        for (int num : nums) {
            if (num == ele1) {
                cnt1 += 1;
            } else if (num == ele2) {
                cnt2 += 1;
            }
        }
        List res = new ArrayList<>();
        if (cnt1 > nums.length / 3) {
            res.add(ele1);
        }
        if (cnt2 > nums.length / 3) {
            res.add(ele2);
        }
        return res;
    }   
}