前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 347. 前 K 个高频元素(哈希/优先队列)

LeetCode 347. 前 K 个高频元素(哈希/优先队列)

作者头像
Michael阿明
发布2020-07-13 15:26:12
2190
发布2020-07-13 15:26:12
举报

1. 题目

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:
输入: nums = [1], k = 1
输出: [1]
说明:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/top-k-frequent-elements 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

2.1 哈希

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> m;
        vector<int> ans;
        for(int num:nums)
        	m[num]++;
        vector<pair<int,int>> v(m.begin(), m.end());//map不支持排序,转成vector
        sort(v.begin(), v.end(),[](pair<int,int> &a, pair<int,int> &b)
        		{return a.second > b.second;});	//新的比较函数写法
        auto it = v.begin();
        while(k--)
        {
        	ans.push_back(it->first);
        	++it;
        }
        return ans;
    }
};
在这里插入图片描述
在这里插入图片描述

2.2 优先队列

class Solution {
	struct cmp//必须写struct,不能写class
	{
		bool operator()(pair<int, int>& a, pair<int, int>& b)
		{ return a.second > b.second; }//小顶堆
	};
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> m;
        vector<int> ans;
        for(int num:nums)
        	m[num]++;
        priority_queue<pair<int,int>,vector<pair<int,int>>, cmp> q;
        for(auto a:m)
        {
        	q.push(a);
        	if(q.size() > k)
        		q.pop();
        }
        while(!q.empty())
        {
        	ans.push_back(q.top().first);
        	q.pop();
        }
        return ans;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
    • 2.1 哈希
      • 2.2 优先队列
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档