I’ve just done a problem on Leetcode. But I were confused about the sort() function of C++. This’s more detail about it
- Problem: 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
Hear 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]
Thing that I don’t understand is why the second one’s sort() function seems not working. Can anybody help me to make it clear, please. Many thanks!!!
I try two code snippets with the same function but it seems return back the two differnt 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.