Answers for "element present in array more than n/2 time"

0

element present in array more than n/2 time

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> l =  new ArrayList<Integer>();
        
        int n1 = -1;
        int t1 = 0;
        int n2 = -1;
        int t2 = 0;
        
        for(int i=0;i<nums.length;i++){
            
            if(n1==nums[i]){
                t1++;
            }
            else if(n2==nums[i]){
                t2++;
            }
            else if(t1==0){
                n1 = nums[i];
                t1 = 1;
            }
            else if(t2==0){
                n2 = nums[i];
                t2 = 1;
            }
            else{
                t1--;
                t2--;
            }
            
        }
        int c1=0,c2 = 0;
        
        for(int i=0;i<nums.length;i++){
            if(n1==nums[i]){
                c1++;
            }
            else if(n2==nums[i]){
                c2++;
            }
        }
        
        if(c1>(nums.length/3)){
            l.add(n1);
        }
        
        if(c2>(nums.length/3)){
            l.add(n2);
        }
        
        return l;
    }
}
Posted by: Guest on August-13-2021

Code answers related to "element present in array more than n/2 time"

Browse Popular Code Answers by Language