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.
-
1 public class Solution { 2 public List<Integer> topKFrequent(int[] nums, int k) { 3 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 4 for (int num : nums) { 5 if ( map.containsKey(num) ) 6 map.put( num, map.get(num) + 1); 7 else 8 map.put( num, 1 ); 9 } 10 11 PriorityQueue<Map.Entry<Integer, Integer> > pq = new PriorityQueue<>( 12 new Comparator<Map.Entry<Integer, Integer> >() { 13 public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) { 14 return b.getValue() - a.getValue(); 15 } 16 } 17 ); 18 pq.addAll(map.entrySet()); 19 20 List<Integer> result = new ArrayList<>(); 21 for (int i = 0; i < k; i++) { 22 if (!pq.isEmpty()) { 23 result.add(pq.poll().getKey()); 24 } else break; 25 } 26 return result; 27 } 28 }