692. 前K个高频单词

  1. class Solution {
  2. public List<String> topKFrequent(String[] words, int k) {
  3. List<String> ans = new ArrayList<>();
  4. // 单词频率统计
  5. Map<String, Integer> map = new HashMap<>();
  6. for (String word : words) {
  7. if (!map.containsKey(word)) {
  8. map.put(word, 1);
  9. } else {
  10. map.put(word, map.get(word) + 1);
  11. }
  12. }
  13. // 出现次数相同时按照字母顺序进行排序,出现次数不同时按照频率进行排序;
  14. PriorityQueue<String> minHeap = new PriorityQueue<>(
  15. (o1, o2) -> (map.get(o1) == map.get(o2) ? o2.compareTo(o1) : map.get(o1) - map.get(o2))
  16. );
  17. for (String word : map.keySet()) {
  18. minHeap.offer(word);
  19. if (minHeap.size() > k)
  20. minHeap.poll();
  21. }
  22. for (int i = 0; i < k; i++) {
  23. ans.add(minHeap.remove());
  24. }
  25. Collections.reverse(ans);
  26. return ans;
  27. }
  28. }