347. Top K Frequent Elements

1. use maxHeap,

O(nlogn), O(n)

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        // 1. use hashmap to store freq
        // 2. use maxheap or bucket sort to find top k freq elements
        
        Map<Integer, Integer> map = new HashMap<>();
        for (int n : nums) {
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> map.get(b) - map.get(a));
        
        maxHeap.addAll(map.keySet());
        
        List<Integer> result = new ArrayList<>();
        for (int i = maxHeap.size() - 1; i >=0 && result.size() < k; i--) {
            result.add(maxHeap.remove());
        }
        
        return result.stream().mapToInt(i->i).toArray();
        
    }
}

2. use minHeap

T: O(nlogk)

S: O(n)

2. use bucket sort

O(n), O(n)

Last updated

Was this helpful?