LeetCode 347. Top K Frequent Elements 前 K 个高频元素 (Java)
题目:
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where nis the array's size.
- It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
- You can return the answer in any order.
分析:
找出前K个高频元素,TopK的问题一般都可以利用堆,或者优先级队列来处理,统计好每个元素出现的顺序,加入到容量大小为k的堆中,即可得到答案。
程序:
class Solution { public int[] topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for(int num:nums){ int times = map.getOrDefault(num, 0); map.put(num, times+1); } PriorityQueue<Integer> minHeap = new PriorityQueue<>((a, b)->{ return map.get(a) - map.get(b); }); for(int num:map.keySet()){ minHeap.offer(num); if(minHeap.size() > k) minHeap.poll(); } int[] res = new int[k]; for(int i = 0; i < res.length; ++i){ res[i] = minHeap.poll(); } return res; } }