Data structure used, hash table and min heap.
A hashmap to save every element along with its frequency for the input data.
A min heap to save top k most frequent map entry, comparing by map.value that is frequency.
Time complexity, O(nlogK).
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
// A hashmap to save <num, frequency> pairs
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
// A min heap to save top k frequent element
Queue<Map.Entry<Integer,Integer>> heap = new PriorityQueue<>(Map.Entry.comparingByValue());
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
heap.offer(e);
if (heap.size() > k) {
heap.poll();
}
}
// Get the numbers with high frequency
List<Integer> res = new ArrayList<Integer>();
while (!heap.isEmpty()) {
res.add(heap.poll().getKey());
}
return res;
}
}