Top K Frequent Elements
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer,Integer> map= new HashMap<>();
for(int num:nums)
{
map.put(num,map.getOrDefault(num,0)+1);
}
PriorityQueue<Map.Entry<Integer,Integer>> heap= new PriorityQueue<>((a,b)->a.getValue()-b.getValue());
for(Map.Entry<Integer,Integer> entry:map.entrySet())
{
heap.offer(entry);
if(heap.size()>k)
{
heap.poll();
}
}
int [] topk=new int[k];
int i=0;
while(!heap.isEmpty())
{
topk[i++]=heap.poll().getKey();
}
return topk;
}
}
If frequencies are equal, how can I pick the key which has a larger value?”
This means:
Among elements with the same frequency, prefer the one with the larger number (key).
Normally, you sort by frequency:
(a, b) -> a.getValue() - b.getValue()
To prefer larger key
(number) when frequency is equal, change comparator to
(a, b) -> {
if (a.getValue().equals(b.getValue())) {
return b.getKey() - a.getKey(); // prefer bigger key
}
return a.getValue() - b.getValue(); // smaller frequency first
}
Comments
Post a Comment