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] ;
}
};
---------------------------------------------------------------------------------
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
Post a Comment