347. Top K Frequent Elements
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 n is the array's size.
-
// use maxHeap. Put entry into maxHeap so we can always poll a number with largest frequency class Solution { public List<Integer> topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for(int n: nums){ // map.put(n, map.getOrDefault(n,0)+1); if(!map.containsKey(n)){ map.put(n, 1); }else{ map.put(n, map.get(n) + 1); } } PriorityQueue<Map.Entry<Integer, Integer>> maxHeap = new PriorityQueue<>((a,b)->(b.getValue()-a.getValue())); for(Map.Entry<Integer,Integer> entry: map.entrySet()){ maxHeap.add(entry); } List<Integer> res = new ArrayList<>(); while(res.size()<k){ Map.Entry<Integer, Integer> entry = maxHeap.poll(); res.add(entry.getKey()); } return res; } }
posted on 2018-08-10 15:19 猪猪🐷 阅读(128) 评论(0) 收藏 举报
浙公网安备 33010602011771号