229. Majority Element II - Medium

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]

 

there're at most 2 candidates, use voting algorithm
use two counters for two candidates

time = O(n), space = O(1)

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        if(nums == null || nums.length == 0) {
            return new ArrayList<>();
        }
        int number1 = nums[0], counter1 = 0;
        int number2 = nums[0], counter2 = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == number1) {
                counter1++;
            } else if(nums[i] == number2) {
                counter2++;
            } else if(counter1 == 0) {
                counter1++;
                number1 = nums[i];
            } else if(counter2 == 0) {
                counter2++;
                number2 = nums[i];
            } else {
                counter1--;
                counter2--;
            }
        }
        
        counter1 = 0; counter2 = 0;
        for(int x : nums) {
            if(x == number1) {
                counter1++;
            } else if(x == number2) {
                counter2++;
            }
        }
        
        List<Integer> res = new ArrayList<>();
        if(counter1 > nums.length / 3) {
            res.add(number1);
        }
        if(counter2 > nums.length / 3) {
            res.add(number2);
        }
        return res;
    }
}

 

posted @ 2020-09-22 16:15  fatttcat  阅读(100)  评论(0编辑  收藏  举报