# Sort the array in ascending order according to the frequency

2020-11-06 01:14:51

### Background

The first time I've tried to do the double week , It turned out to be a failure with this question . The first 38 The first question of a biweekly match , Simple questions , I can't answer ....

### Problem solving

【c++】 I took a look at other people's methods ,C++ It's usually used first cnt Array to calculate the frequency , Using sort（nums.begin(),nums.end(), Temporary method ）;

``````class Solution {
public:
vector<int> frequencySort(vector<int>& nums) {
unordered_map<int, int> cnt;
for (auto n : nums) {
cnt[n]++;
}
sort(nums.begin(), nums.end(), [&cnt](int a, int b) {
return (cnt[a] == cnt[b]) ? a > b : cnt[a] < cnt[b];
});
return nums;
}
};
``````

【JAVA】 And found a better way , Put... Directly -100 <= nums[i] <= 100 use cnt The array mentions 200, It's just , Wonderful ！

``````class Solution {
public int[] frequencySort(int[] nums) {
int[] cnts = new int;
for (int n : nums){
cnts[n + 100] ++;
}
for (int i = 0; i < nums.length; i ++){
nums[i] = 10000 * cnts[nums[i] + 100] - nums[i] + 100;
}
Arrays.sort(nums);

for (int i = 0; i < nums.length; i ++){
nums[i] = 100 - nums[i] % 10000 ;
}

return nums;
}
}
``````

The source of the code is