zoukankan      html  css  js  c++  java
  • [leetcode]692. Top K Frequent Words 最高频K个单词

    Given a non-empty list of words, return the k most frequent elements.

    Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

    Example 1:

    Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
    Output: ["i", "love"]
    Explanation: "i" and "love" are the two most frequent words.
        Note that "i" comes before "love" due to a lower alphabetical order

    题目

    思路

    1. Using HashMap and PriorityQueue
    2. Build a HashMap to get the word frequency
    3. PriorityQueue (minHeap) - if the counts are same return higher lexicographically word first so that the lower remains in the queue
    4. We add each entry to PQ. If the PQ size > k, then we pop the lowest value in the PQ.

    [leetcode]347. Top K Frequent Elements K个最常见元素思路完全一致

    代码

     1 /*
     2 Time: O(nlogk)
     3 Space: O(n)
     4 */
     5 
     6 class Solution {
     7        public List<String> topKFrequent(String[] words, int k) {
     8          List<String> result = new LinkedList<>();
     9          // freq map 
    10          Map<String, Integer> map = new HashMap<>();
    11          for(String s: words){
    12              map.put(s, map.containsKey(s) ? map.get(s) + 1 : 1);
    13          }
    14         // b.getKey().compareTo(a.getKey()) 处理了频率相同,按字典顺序排列的题意要求
    15          PriorityQueue<Map.Entry<String, Integer>> minHeap = new PriorityQueue<>(
    16                  (a,b) -> a.getValue()==b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue()-b.getValue()
    17          );
    18 
    19          for(Map.Entry<String, Integer> entry: map.entrySet())
    20          {
    21              minHeap.offer(entry);
    22              if(minHeap.size()>k)
    23                  // 自定义从小到大的顺序保证了poll出来的是较小值,留在minHeap里的是较大值
    24                  minHeap.poll();
    25          }
    26 
    27          while(!minHeap.isEmpty())
    28              result.add(0, minHeap.poll().getKey());
    29 
    30          return result;
    31      }
    32 }
  • 相关阅读:
    vagrant 入门3
    vagrant 入门4
    vagrant 入门2
    Map、Debug追踪
    Comparator比较器 、Comparable接口
    File类
    Lambda表达式、函数式编程思想概述
    异常--异常体系、异常的处理、异常的捕获、finally语句块和自定义异常
    List集合、Set集合、Collection集合工具类
    数据结构---栈、队列、数组、链表和红黑树
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9824013.html
Copyright © 2011-2022 走看看