【堆】Leetcode692:前k个高频单词_List

 

【堆】Leetcode692:前k个高频单词_List_02

 

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
    Map<String,Integer>map=new HashMap<>(words.length);
    //建立哈希表统计单词频率
    for(String word:words){
        map.put(word,map.getOrDefault(word,0)+1);
    }
    //小顶堆,自定义排序规则
     PriorityQueue<String>minheap=new PriorityQueue<>((o1,o2)->{
Integer o1Count=map.get(o1);
Integer o2Count=map.get(o2);
if(o1Count.equals(o2Count)){
    return o2.compareTo(o1);
}
else{
    return o1Count-o2Count;
}});
//维持topk频率的单词
for(String word:map.keySet()){
        minheap.add(word);
        if(minheap.size()>k){
            minheap.poll();
        }
}
//利用栈特性
LinkedList<String>stack=new LinkedList<>();
while(!minheap.isEmpty()){
    stack.push(minheap.poll());
}
return stack;
    }
     };
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.