Task: design a function such that it returns a sorted vector pair with highest frequency element first and if two elements have same frequency, arrange them in sorted order(increasing) by element.
Does it have any conceptual error?
Is it possible to further decrease it's complexity
in:
1 2 4 8 4 9 2 0 9 4 2out: number frequency
2 3 4 3 9 2 0 1 1 1 8 1
len(v):
10^6v[i]:
10^15
#include <bits/stdc++.h>
using namespace std;
// sort function
bool mySort(pair<long long,long long> &a, pair<long long,long long>&b){
if(a.second==b.second)
return (a.first<b.first);
else
return (a.second>b.second);
}
vector<pair<long long, long long> > sortWithFrequency(vector<long long> v){
vector<pair<long long, long long> > v_new;
map<long long, long long> m;
vector<long long>::iterator p= v.begin();
while(p!=v.end()){
m[*p]+=1;
p++;
}
map<long long, long long>::iterator mp = m.begin();
while(mp!=m.end()){
v_new.push_back(pair<long long,long long>((*mp).first,(*mp).second));
mp++;
}
sort(v_new.begin(), v_new.end(), mySort);
return v_new;
}
int main() {
long long testcase;
cin>>testcase;
while(testcase--){
long long N;
cin >> N;
// declaring vector
vector<long long> v;
for(long long i = 0;i<N;i++){
long long k;
cin >> k;
v.push_back(k);
}
// calling function to perform required operation
vector<pair<long long, long long> > v_new = sortWithFrequency(v);
vector<pair<long long, long long> >::iterator it;
for(it = v_new.begin();it!=v_new.end();it++){
cout << it->first << " " << it->second << " ";
}
cout << endl;
}
return 0;
}