python实现:
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
frequency = collections.Counter(words)
# 大顶堆:最小的在下面,最大的在上面,弹出k个
queue = [(-freq, word)for word,freq in frequency.items()]
heapq.heapify(queue)
return [heapq.heappop(queue)[1] for _ in range(k)]
Java实现:
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String,Integer> count = new HashMap();
for(String word:words){
count.put(word,count.getOrDefault(word,0)+1);
}
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1,w2) -> count.get(w1).equals(count.get(w2))? w2.compareTo(w1):count.get(w1)
-count.get(w2) );
for(String word:count.keySet()){
heap.offer(word);
if(heap.size()>k) heap.poll();
}
List<String> ans = new ArrayList();
while (!heap.isEmpty()) ans.add(heap.poll());
Collections.reverse(ans);
return ans;
}
}