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;
    }
};
相关推荐
执着25919 分钟前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
2501_9011478321 分钟前
学习笔记:单调递增数字求解的迭代优化与工程实践
linux·服务器·笔记·学习·算法
AI科技星24 分钟前
张祥前统一场论核心场方程的经典验证-基于电子与质子的求导溯源及力的精确计算
线性代数·算法·机器学习·矩阵·概率论
kebijuelun29 分钟前
ERNIE 5.0:统一自回归多模态与弹性训练
人工智能·算法·语言模型·transformer
历程里程碑1 小时前
普通数组----最大子数组和
大数据·算法·elasticsearch·搜索引擎·排序算法·哈希算法·散列表
52Hz1181 小时前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode
苦藤新鸡1 小时前
56.组合总数
数据结构·算法·leetcode
LiLiYuan.1 小时前
【Cursor 中找不到LeetCode 插件解决办法】
算法·leetcode·职场和发展
Charlie_lll2 小时前
力扣解题-[3379]转换数组
数据结构·后端·算法·leetcode