Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
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 n is the array's size.
题意:
给定数组,求其中出现频率最高的K个元素。
Solution: PriorityQueue
扫数组,将数组每个元素和其对应的出现频率存到Map里
扫Map,将Map里的元素放入maxHeap
从maxHeap里poll出K个元素即可
code
1 class Solution { 2 public List<Integer> topKFrequent(int[] nums, int k) { 3 Map<Integer, Integer> numFreqs = new HashMap(); 4 5 for(int num : nums){ 6 numFreqs.put(num, numFreqs.containsKey(num) ? numFreqs.get(num) + 1 : 1); 7 } 8 9 PriorityQueue <Map.Entry<Integer, Integer>> maxHeap = new PriorityQueue<>((entry1, entry2) -> entry2.getValue() - entry1.getValue()); 10 11 12 for(Map.Entry<Integer, Integer> entry : numFreqs.entrySet()){ 13 maxHeap.add(entry); 14 } 15 16 List<Integer> result = new ArrayList<>(); 17 while(!maxHeap.isEmpty() && result.size() < k){ 18 result.add(0, maxHeap.poll().getKey()); 19 } 20 return result; 21 22 } 23 }