1636.按照频率将数组升序排序
链接:1636.按照频率将数组升序排序
难度:Easy
标签:数组、哈希表、排序
简介:给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 。
题解 1 - cpp
- 编辑时间:2022-09-19
- 执行用时:4ms
- 内存消耗:10.9MB
- 编程语言:cpp
- 解法介绍:用哈希表存储后排序。
class Solution {
public:
    typedef pair<int, int> node;
    vector<int> frequencySort(vector<int>& nums) {
        unordered_map<int, int> m;
        for (auto &num : nums) m[num]++;
        vector<node> list;
        for (auto &item : m) list.push_back(item);
        sort(list.begin(), list.end(), [&](const node a, const node b) -> bool {
            return a.second == b.second ? b.first < a.first : a.second < b.second;
        });
        vector<int> ans;
        ans.reserve(nums.size());
        for (auto &item : list) for (int i = 0; i < item.second; i++) ans.push_back(item.first);
        return ans;
    }
};