最常用的k个元素 347. Top K Frequent Elements
作者:互联网
用max heap
// use maxHeap. Put entry into maxHeap so we can always poll a number with largest frequency public 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); } 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; } }
标签:map,Elements,int,res,Top,maxHeap,347,new,entry 来源: https://www.cnblogs.com/immiao0319/p/16214973.html