当前位置:网站首页>Sort the array in ascending order according to the frequency

Sort the array in ascending order according to the frequency

2020-11-06 01:14:00 Chasing_best

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;
    }
};

This code comes from

【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[201];
        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

版权声明
本文为[Chasing_best]所创,转载请带上原文链接,感谢