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.
思路:其实思路很简单。扫一遍array,把数和次数存到hashmap。然后按照次数大的priority把entry存到prioirty queue里面。最后按照k的个数依次从priority queue里面读出来。有Map.Entry这个神奇包裹省事很多。
Map.Entry:https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
public class Solution { public ListtopKFrequent(int[] nums, int k) { List save=new ArrayList (); if(nums.length==0) { return save; } Map res=new HashMap (); for(int i=0;i > maxHeap = new PriorityQueue<>((a,b)->(b.getValue()-a.getValue())); for(Map.Entry entry:res.entrySet()) { maxHeap.add(entry); } while(save.size() entry = maxHeap.poll(); save.add(entry.getKey()); } return save; }}