Majority Element @LeetCode < Moore’s Voting Algorithm >

PROBLEM :

Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times.

You may assume that the array is non-empty and the majority element always exist in the array.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        if(nums.size()==1)
            return nums[0] ;
         
        int maj=CheckMajEle(nums) ;
     
        int count=0 ;
        for(int i=0;i<nums.size();i++)
            if(nums[i]==maj)
                count++ ;
             
        if(count>nums.size()/2)
            return maj ;
    }
 
    int CheckMajEle(vector<int> &nums){
        int count=1 ;
        int index=0 ;
     
        int i ;
        for(i=1;i<nums.size();i++){
            if(nums[i]==nums[index])
                count++ ;
            else
                count-- ;
             
            if(count==0){
                index=i ;
                count=1 ;
            }
        }
        return nums[index] ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )