Problem Statement
You are given a list of a repeated set of integers. Your task for the problem is to return a list of the given elements in decreasing sorted order of their frequency of repetition in the given list with the element with the highest frequency of repetition first and so on. Note: If two numbers have the same frequency then keep the one that was present before the other in the original given list (array) first.
INPUT:
1 3 2 2 2 3 4 3 1
OUTPUT:
3 3 3 2 2 2 1 1 4
Code:
#include <bits/stdc++.h>
using namespace std;
vector<int> sortByFrequency(vector<int>& nums){
unordered_map <int,int> mpp;
vector <int> temp;
for(int i=0;i<nums.size();i++)
{
mpp[nums[i]]++;
}
int max_ele;
int max = INT_MIN;
while(mpp.empty()==0)
{
for(auto it : mpp)
{
if (it.second > max) {
max = it.second;
max_ele = it.first;
}
}
while(max--)
{
temp.push_back(max_ele);
}
mpp.erase(max_ele);
}
return temp;
}
int main()
{
vector <int> arr = {1, 3, 2, 2, 2, 3, 4, 3, 1};
vector <int> res;
res = sortByFrequency(arr);
for(auto it: res)
{
cout << it << " ";
}
}
This code gives the output of:
2 2 2 3 3 3 1 1 4
But Actual output should be:
3 3 3 2 2 2 1 1 4
That is it violates this condition If two numbers have the same frequency then keep the one that was present before the other in the original given list (array) first.
How can I solve this?