I’ve just done a problem on Leetcode. But I was confused about the sort() function of C++.
This is more detail about it:
Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
–Input: An array
–Output: Sorted array following the problem’s rule
Here is my code.
First code snippet:
class Solution {
public:
vector<int> frequencySort(vector<int>& nums) {
std::map<int, int> hm;
for (int numb : nums)
hm[numb] ++ ;
sort(nums.begin(), nums.end(), [&](int a,int b){
if(hm[a] == hm[b])
return a > b;
return hm[a] < hm[b];
});
}
}
The second code snippet:
class Solution {
public:
vector<int> frequencySort(vector<int>& nums) {
std::map<int, int> hm;
for (int numb : nums)
hm[numb] ++ ;
sort(nums.begin(), nums.end(), [&](int a,int b){
if(hm[a] == hm[b])
return a > b;
return hm[a] < hm[b];
});
return nums;
vector<int> arr;
for(auto &[numb,freq] : hm){
while(freq > 0){
arr.push_back(numb);
freq--;
}
}
std::sort(arr.begin(), arr.end(), [&](int a, int b){
if( hm[a] == hm[b])
return a > b;
else
return hm[a] < hm[b];
});
return arr;
}
};
Here’s an example
-Input: [1,1,2,2,2,3]
-Output for first code snippet: [3,1,1,2,2,2]
-Output for second code snippet: [3,2,2,2,1,1]
The thing that I don’t understand is why the second one’s sort() function seems to not be working? Can anybody help me to make it clear, please?
I tried two code snippets with the same function but it seems to return two different results.
David Adonis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5