Below is one of many algorithm to find maximum frequency of element in a Vector.
Algorithm Used:
#include<iostream>
#include <vector>
#include <map>
using namespace std;
int MaxFrequency(vector<int> v,int& freq)
{
int maxElement=0;
map<int,int> m;
for(int i=0;i<v.size();i++)
{
m[v[i]]= ++m[v[i]];
}
for(map<int,int>::iterator i=m.begin();i!=m.end();i++)
{
if((*i).second>freq)
{
freq= (*i).second;
maxElement = (*i).first;
}
}
return maxElement;
}
int main()
{
int x,n,max=0,f=0;
cin>>n;
vector<int> a;
for(int i=0;i<n;i++)
{
cin>>x;
a.push_back(x);
}
cout<<"Max Repeating element is: " <<MaxFrequency(a,f)<<" with Frequency: ";
cout<<f;
return 0;
}
Please comment if you find anything incorrect.
Algorithm Used:
- Take a map <int,int> where its key is vector element and value is element count.
- Iterate over the vector thereby incrementing element count in a map (map value by default is assigned to zero)
- Iterate over the map by checking its value with maximum frequency till now.
- Return the maximum repeated element and also get its frequency.
#include<iostream>
#include <vector>
#include <map>
using namespace std;
int MaxFrequency(vector<int> v,int& freq)
{
int maxElement=0;
map<int,int> m;
for(int i=0;i<v.size();i++)
{
m[v[i]]= ++m[v[i]];
}
for(map<int,int>::iterator i=m.begin();i!=m.end();i++)
{
if((*i).second>freq)
{
freq= (*i).second;
maxElement = (*i).first;
}
}
return maxElement;
}
int main()
{
int x,n,max=0,f=0;
cin>>n;
vector<int> a;
for(int i=0;i<n;i++)
{
cin>>x;
a.push_back(x);
}
cout<<"Max Repeating element is: " <<MaxFrequency(a,f)<<" with Frequency: ";
cout<<f;
return 0;
}
Please comment if you find anything incorrect.
No comments:
Post a Comment