347. 前 K 个高频元素 分别使用sort和priority_queue 对哈希结构自定义排序

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例 1:

**输入:**nums = [1,1,1,2,2,3], k = 2

输出:[1,2]

示例 2:

**输入:**nums = [1], k = 1

输出:[1]

示例 3:

**输入:**nums = [1,2,1,2,1,2,3,1,3,2], k = 2

输出:[1,2]

解法一:首先使用哈希表来进行计数

然后利用sort库函数来进行排序,但是这个排序只能针对序列式容器,所以需要使用vector<pair<int,int>>temp来进行存储

使用lambda表达式给sort传对象

Lambda 就是一个 匿名的仿函数对象

cpp 复制代码
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;
        unordered_map<int, int> dict; // 用哈希表来计数每个值出现的次数
        for(auto e : nums)
            dict[e]++;
        // 因为哈希结构是关联式容器,想使用sort排序必须放入vector这样的序列式容器中
        vector<pair<int,int>> temp; // 用vector<>来存储哈希结构的pair  
        for(auto &e : dict)         // 每个 e 就是 pair<int, int>
            temp.push_back(e);      // cout << p.first << ", " << p.second << endl; 

        sort(temp.begin(), temp.end(),   // 使用sort的lammbda表达式
            [](const auto &left, const auto &right)
            {
                return left.second > right.second;
            });

        for(int i = 0; i < k; i++)
        {
            res.push_back(temp[i].first);
        }
        return res;
    }
};

另外排序可以使用下面的lambda表达式 也可以使用仿函数

使用仿函数给sort传对象

cpp 复制代码
class Com
{
public:  // 1.没有用public 修饰
    // 2 没有bool修饰   
    // 3 参数错误用的vector<pair<int,int>>  sort() 会把 元素本身传入比较器,也就是:pair<int,int>
    // 	例如只是对简单int类型数组进行排序就是  bool operator()(const int& left, const int& right)
    bool operator()(const pair<int,int> &left, const pair<int,int> &right)
    {
        return left.second > right.second;
    }
};

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;
        unordered_map<int, int> dict; // 用哈希表来计数每个值出现的次数
        for(auto e : nums)
            dict[e]++;
        // 因为哈希结构是关联式容器,想使用sort排序必须放入vector这样的序列式容器中
        vector<pair<int,int>> temp; // 用vector<>来存储哈希结构的pair  
        for(auto &e : dict)         // 每个 e 就是 pair<int, int>
            temp.push_back(e);      // cout << p.first << ", " << p.second << endl; 

        sort(temp.begin(), temp.end(), Com());

        for(int i = 0; i < k; i++)
        {
            res.push_back(temp[i].first);
        }
        return res;
    }
};

对哈希结构迭代器的再认知:

使用返回for访问每个元素,每个元素都是一个pair<int, int>

cpp 复制代码
for(auto &e : dict)         // 每个 e 就是 pair<int, int>
    temp.push_back(e);      // cout << e.first << ", " << e.second << endl; 

使用迭代器从头到尾访问map,每个迭代器it 解引用之后就是e

cpp 复制代码
 for (auto it = mp.begin(); it != mp.end(); ++it) {

     cout << it->first << " " << it->second << endl;}

(*it) == e == pair<int, int>

(*it).second == e.second == it->second

解法二:使用priority_queue来排序

注意区分,二者传参时的不同,sort函数需要一个对象,传入一个匿名对象Com()

而优先级队列,需要的是一个类型,它内部会自己进行构造

cpp 复制代码
class Com
{
public:  // 1.没有用public 修饰
    // 2 没有bool修饰   
    // 3 参数错误用的vector<pair<int,int>>  sort() 会把 元素本身传入比较器,也就是:pair<int,int>
    // 	例如只是对简单int类型数组进行排序就是  bool operator()(const int& left, const int& right)
    bool operator()(const pair<int,int> &left, const pair<int,int> &right)
    {
        return left.second < right.second;
    }
};

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;
        unordered_map<int, int> dict; // 用哈希表来计数每个值出现的次数
        for(auto e : nums)
            dict[e]++;
        priority_queue <pair<int,int>, vector<pair<int, int>>, Com> q; // 注意这里和sort库函数的区别
        for(auto &e : dict)
        {
            q.push(e);
        }

        for(int i = 0; i < k; i++)
        {
            res.push_back(q.top().first);
            q.pop();
        }
        return res;
    }
};
相关推荐
那个村的李富贵7 小时前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
power 雀儿7 小时前
Scaled Dot-Product Attention 分数计算 C++
算法
琹箐8 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
renhongxia18 小时前
如何基于知识图谱进行故障原因、事故原因推理,需要用到哪些算法
人工智能·深度学习·算法·机器学习·自然语言处理·transformer·知识图谱
坚持就完事了8 小时前
数据结构之树(Java实现)
java·算法
算法备案代理8 小时前
大模型备案与算法备案,企业该如何选择?
人工智能·算法·大模型·算法备案
赛姐在努力.9 小时前
【拓扑排序】-- 算法原理讲解,及实现拓扑排序,附赠热门例题
java·算法·图论
野犬寒鸦10 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
霖霖总总10 小时前
[小技巧66]当自增主键耗尽:MySQL 主键溢出问题深度解析与雪花算法替代方案
mysql·算法
rainbow688910 小时前
深入解析C++STL:map与set底层奥秘
java·数据结构·算法