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;
    }
};
相关推荐
小李小李快乐不已1 小时前
图论理论基础(3)
数据结构·c++·算法·图论
牙牙要健康1 小时前
【open3d】示例:自动计算点人脸点云模型面部朝向算法
人工智能·python·算法
youngee111 小时前
hot100-41二叉搜索树中第K小的元素
算法
mmz12072 小时前
双指针问题5(c++)
c++·算法
星空露珠2 小时前
lua获取随机颜色rgb转换hex
数据结构·数据库·算法·游戏·lua
mit6.8242 小时前
预hash|vector<int> dfs
算法
Zsy_0510032 小时前
【数据结构】堆简单介绍、C语言实现堆和堆排序
c语言·数据结构·算法
Rock_yzh2 小时前
LeetCode算法刷题——56. 合并区间
数据结构·c++·学习·算法·leetcode·职场和发展·动态规划
sheeta19982 小时前
LeetCode 每日一题笔记 日期:2025.12.02 题目:3623. 统计梯形的数目 I
笔记·算法·leetcode