题目:347. 前 K 个高频元素
思路:用哈希表来记录每个元素出现的次数,然后使用优先队列即可。时间复杂度优于0(nlogn)。
C++版本:
class Solution {
public:
typedef pair<int,int> PII;
vector<int> topKFrequent(vector<int>& nums, int k) {
//哈希表记录每个元素出现的次数
unordered_map<int,int> mp;
for(auto x:nums){
mp[x]++;
}
//使用优先队列
priority_queue<PII> qu;
for(auto &t:mp){
qu.push({t.second,t.first});
}
//前k个高频元素
vector<int> v;
int ans=0;
while(ans<k){
PII tmp=qu.top();
qu.pop();
v.push_back(tmp.second);
ans++;
}
return v;
}
};
JAVA版本:
class Solution {
public int[] topKFrequent(int[] nums, int k) {
//哈希表记录每个元素出现的次数
Map<Integer,Integer> mp=new HashMap<Integer,Integer>();
for(var x:nums){
mp.put(x,mp.getOrDefault(x,0)+1);
}
//使用优先队列
PriorityQueue<Map.Entry<Integer,Integer>> qu = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
for(var x:mp.entrySet()){
qu.offer(x);
}
//前k个高频元素
int[] v=new int[k];
int ans=0;
while(ans<k){
v[ans++]=qu.poll().getKey();
}
return v;
}
}