AMCAT Automata Fix Sample Question-5

Program 5

MAJORITY ELEMENT

Rahul is a student at an engineering college and is learning coding to be well prepared for the upcoming hackathon.

 

Rahul encounters a tough coding question and got stuck.

 
Consider an array with a size of n. Your task is to identify and return the majority element in the array. The majority element refers to the element that appears more than [ n/2 ] times. You can assume that the majority element always exists in the array.

Try solving and help rahul.

 

int majorityElement(vector& nums) {
    	int majority,count=0;
    	for(int i=0;i< nums.size();i++)
    	{
        	if(count)
        	{
            	   count+=(nums[i]==majority ? 1 : -1);
        	}
        	else
        	{
            	   Majority += nums[i];
            	   count=1;
        	}
    	}
    	return majority;
};

int majorityElement(vector& nums) {
    	int majority,count=0;
    	for(int i=0;i< nums.size();i++)
    	{
        	if(count)
        	{
            	  count+=(nums[i]==majority ? 1 : -1);
        	}
        	else
        	{
            	  majority=nums[i];
            	  count=1;
        	}
    	}
    	return majority;
};