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;
    }
};
相关推荐
CoovallyAIHub4 分钟前
自顶向下 or 自底向上?姿态估计技术是如何进化的?
深度学习·算法·计算机视觉
q_302381955614 分钟前
14.7MB轻量模型!NVIDIA Jetson边缘设备解锁工厂设备故障预警新方案
人工智能·python·算法·ascend·算子开发
爱敲点代码的小哥22 分钟前
C#哈希表遍历技巧全解析以及栈 堆 队列的认识
算法·哈希算法
xiaoxue..24 分钟前
爬楼梯问题:从递归到动态规划再到闭包的进化之路
javascript·算法·面试·动态规划
CoovallyAIHub27 分钟前
YOLO11算法深度解析:四大工业场景实战,开源数据集助力AI质检落地
深度学习·算法·计算机视觉
import_random32 分钟前
[推荐]embedding嵌入表示是如何生成的(实战)
算法
chao18984434 分钟前
基于布谷鸟搜索算法的分布式电源多目标选址定容
算法
Xの哲學35 分钟前
Linux IPsec 深度解析: 架构, 原理与实战指南
linux·服务器·网络·算法·边缘计算
Swift社区35 分钟前
LeetCode 455 - 分发饼干
算法·leetcode·职场和发展
会编程是什么感觉...35 分钟前
算法 - FOC
线性代数·算法·矩阵·无刷电机