LeetCode 347. Top K Frequent Elements (前K个高频元素)

题目标签:HashMap, Heap

  题目给了我们一组数字,让我们找出 k 个 最多出现的数字。

  先把数字和出现次数存入hashmap,然后遍历map里的数字,利用priorityQueue,按照出现次数 从小到大的顺序依次把数字 加入 queue。当达到k个数字后,把剩下的都去除。

  最后output的 array,里面顺序是不影响的。

Java Solution:

Runtime: 43 ms, faster than 38% 

Memory Usage: 41 MB, less than 32%

完成日期:04/04/2019

关键点:PriorityQueue

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> result = new ArrayList<>();
        
        // put number and count into map
        for(int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        
        // define priorityQueue
        PriorityQueue<Integer> heap = 
            new PriorityQueue<Integer>((n1, n2) -> map.get(n1) - map.get(n2));
        
        // put each number into heap
        for(int num : map.keySet()) {
            heap.add(num);
            
            if(heap.size() > k) // keep k numbers in the heap
                heap.poll();
        }
        
        // put heap numbers into list
        while(!heap.isEmpty()) {
            result.add(heap.poll());
        }
        
        return result;
    }
}

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

猜你喜欢

转载自www.cnblogs.com/jimmycheng/p/11136060.html