xinyu04

导航

[Oracle] LeetCode 1636 Sort Array by Increasing Frequency 双map

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.

Return the sorted array.

Solution

我们用两个 \(map\) 分别来存储 \(num2freq,freq2num\). 此时对于第二个 \(map\),每一个 \(freq\) 对应着一个 \(vector\), 然后遍历存储即可

点击查看代码
class Solution {
private:
     map<int,vector<int>> freq_num;
     map<int,int> num_freq;
    
public:
    vector<int> frequencySort(vector<int>& nums) {
        int n = nums.size();
        for(int i=0;i<n;i++)num_freq[nums[i]]++;
        for(auto ele:num_freq){
            if(freq_num.count(ele.second)==0)freq_num[ele.second]={ele.first};
            else{
                freq_num[ele.second].push_back(ele.first);
            }
        }
        vector<int> ans;
        for(auto ele: freq_num){
            for(int i=ele.second.size()-1;i>=0;i--){
                for(int k=0;k<ele.first;k++){
                    ans.push_back(ele.second[i]);
                }
            }
        }
        return ans;
    }
};

posted on 2022-09-25 21:33  Blackzxy  阅读(20)  评论(0编辑  收藏  举报