Majority voting agorithms... O(n) complexity


  • 7
    S
        public int majorityElement(int[] nums) {
     if(nums == null || nums.length <= 0)
        return 0;
        
     int majority=1;
     int number = nums[0];
        for(int i =1 ; i < nums.length; i++)
        {
             if(nums[i] !=  number)
                majority--;
             else
             {
                 majority++;
                 continue;
             }
             if(majority == 0){
                 number = nums[i];
                 majority++;
             }
        }
       return number;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.