Leetcode 347. Top K Frequent Elements

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 topKFrequent(int[] nums, int k) {
        // A hashmap to save  pairs
        HashMap map = new HashMap();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        
        // A min heap to save top k frequent element
        Queue> heap = new PriorityQueue<>(Map.Entry.comparingByValue());
        for (Map.Entry e : map.entrySet()) {
            heap.offer(e);
            if (heap.size() > k) {
                heap.poll();
            }
        }

        // Get the numbers with high frequency
        List res = new ArrayList();
        while (!heap.isEmpty()) {
            res.add(heap.poll().getKey());
        }
        
        return res;
    }
}



你可能感兴趣的:(Leetcode,Heap,Hashtable)