【LeetCode & 剑指offer刷题】查找与排序题12:Top K Frequent Elements
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
-
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
-
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
//问题:返回数组中出现频次前k大的元素
using namespace std;
#include <algorithm>
#include <unordered_map>
class Solution
{
public:
vector<int> topKFrequent(vector<int>& a, int k)
{
unordered_map<int,int> counter; //出现频次计数器map
priority_queue<pair<int, int>> q; //注意<pair<int, int>>的用法
vector<int> res; //用于存储结果
for(auto key:a) counter[key]++; //用counter[key]访问map中为key的value,按<数字,频次> 组织map
for(auto it:counter) q.push({it.second, it.first}); //注意使用{}对,按<频次,数字> 组织,构建一个大顶堆(默认)
for(int i=0;i<k; i++)//输出前k个最大值
{
res.push_back(q.top().second);
q.pop();
}
return res;
//时间分析:
//构建map耗时O(n),构建大顶堆O(nlogn),输出前k个数O(klogn),时间复杂度O(nlogn)
}
};
/*无法做出
//计数得统计“直方图”,再用堆排序找前k个元素
#include <algorithm>
class Solution
{
public:
vector<int> topKFrequent(vector<int>& a, int k)
{
vector<int> count(k); //出现频次计数器
for(int i=0; i < a.size(); i++) //频次计数,一次遍历,时间复杂度为O(n)
{
count[a[i]]++;
}
partial_sort(count.begin(), count.begin()+k, count.end(), greater<int>()); //堆排序,时间复杂度为O(klogn)
//注意默认为增序排列,这里要找前k大的数,故比较函数应设置为greater
//程序时间复杂度为O(n+klogn)
}
};*/