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

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();

        int major1 = 0, count1 =0;
        int major2 = 0, count2 =0;

        for(int val : nums){
            if(major1 == val){
                count1++;
            }else if(major2 == val){
                count2++;
            }else if(count1==0){
                major1 = val; 
                count1 =1;
                continue;
            }else if(count2 == 0){
                major2 = val;
                count2 =1;
                continue;
            }else{
                count1--;
                count2--;
            }
        }
        count1 =0;
        count2 =0;
        for(int val : nums){
            if(val == major1) count1++;
            else if(val == major2) count2++;// this else is very important
        }

        if(count1 > nums.length/3) res.add(major1);
        if(count2 > nums.length/3 ) res.add(major2);
        return res;
    }
}

results matching ""

    No results matching ""