Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
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.
- It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
- You can return the answer in any order.
题目链接:https://leetcode.com/problems/top-k-frequent-elements/
思路:先用map统计每个元素出现的次数,因为sort无法直接对map排序,再把元素放到一个vector<pair<int, int>> 中
这题map不需要有序,用unordered_map更快一点。
class Solution {
public:
static bool cmp(pair<int,int> a,pair<int,int>b)
{
return a.second<b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int,int> mp;
vector<int> res;
for(auto it:nums)
{
mp[it]++;
}
vector<pair<int,int>> vc;
for(auto it:mp)
{
vc.emplace_back(make_pair(it.first,it.second));
}
sort(vc.begin(),vc.end(),cmp);
for(int i=0;i<k;i++)
{
res.emplace_back(vc[vc.size()-1-i].first);
}
return res;
}
};
class Solution {
/**
2024年8月22日22:32:33
遍历数组,同时使用map记录每个元素出现的次数,
然后再遍历map,把元素按照次数放到最小堆里,
这个堆里就只会存储前k大的元素了,
最小堆的比较方式要熟悉下怎么自定义写
*/
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map=new HashMap<>();
for(int num:nums){
// 学会使用getOrDefault方法,更简洁
map.put(num,map.getOrDefault(num,0)+1);
// if(map.get(num)==null){
// map.put(num,1);
// } else {
// map.put(num,map.get(num)+1);
// }
}
PriorityQueue<Integer> minHeap=new PriorityQueue<>((a,b)->(map.get(a)-map.get(b)));
for(Integer key:map.keySet()){
minHeap.offer(key);
if(minHeap.size()>k){
minHeap.poll();
}
}
int[] res=new int[k];
int c=0;
while(!minHeap.isEmpty()){
res[c++]=minHeap.poll();
}
return res;
}
}