Runtime: 10 ms, faster than 69.45% of Java online submissions for Top K Frequent Elements.
Memory Usage: 41.8 MB, less than 46.78% of Java online submissions for Top K Frequent Elements.
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int ans[]= new int[k];
// (a,b)-> (b[1] - a[1]) is the ordering we want to apply on the queue
// the ordering is applyed over the second cell of the array which corresponds to the key frequency
PriorityQueue<int[]> queue = new PriorityQueue<>((a,b)-> (b[1] - a[1]));
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++) {
if(map.containsKey(nums[i]))
map.put(nums[i], map.get(nums[i]) + 1);
else
map.put(nums[i], 1);
}
for(int i:map.keySet()){
// add to the priority queue an array with the key and the key frequency
queue.offer(new int[] {i,map.get(i)});
}
for(int i=0; i<k; i++){
ans[i]= queue.poll()[0];
}
return ans;
}
}