I have array of numbers and I have to sort them based on there frequency in ascending order
and if both numbers are same then sort them in decreasing order
what I did was I create unordered_map and store number’s frequency in map
and Inside custom sort function I used it to sort the numbers
Implemention look’s like this
class Solution {
public:
unordered_map<int,int>map;
bool operator ()(const int &a,const int &b){
if(map[a]==map[b])
return a>b;
return map[a]<map[b];
}
vector<int> frequencySort(vector<int>& nums) {
vector<int>answer;
for(auto num:nums)
map[num]++;
sort(nums.begin(),nums.end(),Solution());
return nums;
}
};
but when I use this custom function I gives me wrong answe like
for input nums = [1,1,2,2,2,3]
output is [3,2,2,2,1,1]
which is not expected !! but functions implementation looks good
so what expexted is
Expected [3,1,1,2,2,2]
to achive this I see solution and they used lamda function for custom sorting
Implementation of lamda function is like
sort(nums.begin(),nums.end(),[&](int a, int b) {
if (map[a] == map[b]) {
return a > b;
}
return map[a] < map[b];
});
body part of my function and lamda function is similiar
but why I am getting wrong answer ?
Thank you