• LeetCode 692. Top K Frequent Words


    原题链接在这里:https://leetcode.com/problems/top-k-frequent-words/description/

    题目:

    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.

    Example 2:

    Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
    Output: ["the", "is", "sunny", "day"]
    Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
        with the number of occurrence being 4, 3, 2 and 1 respectively.

    Note:

    1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
    2. Input words contain only lowercase letters.

    Follow up:

    1. Try to solve it in O(n log k) time and O(n) extra space.

    题解:

    利用HashMap<String, Integer> hm储存word和对应的frequency.

    把Map.Entry<String, Integer> entry加到heap中. 

    当heap的size() 大于k 就poll()出一个element.

    最后把heap的所有element的 key string 加进 res中.

    Time Complexity: O(nlogk). n = words.length.

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public List<String> topKFrequent(String[] words, int k) {
     3         List<String> res = new ArrayList<String>();
     4         HashMap<String, Integer> hm = new HashMap<String, Integer>();
     5         for(String s : words){
     6             hm.put(s, hm.getOrDefault(s, 0)+1);
     7         }
     8         
     9         PriorityQueue<Map.Entry<String, Integer>> heap = new PriorityQueue<Map.Entry<String, Integer>>(
    10             (a,b) -> a.getValue() == b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue() - b.getValue()
    11         );
    12         
    13         for(Map.Entry<String, Integer> entry : hm.entrySet()){
    14             heap.add(entry);
    15             if(heap.size() > k){
    16                 heap.poll();
    17             }
    18         }
    19         
    20         while(!heap.isEmpty()){
    21             res.add(0, heap.poll().getKey());
    22         }
    23         return res;
    24     }
    25 }

    类似Top K Frequent Elements.

  • 相关阅读:
    2020.08.28【周报】
    区间合并【排序、栈】
    1042 数字0-9的数量【解题数分DP】
    asp.net数据分页方法
    纯css面板插件,自适应,多样式
    c#winform图表控件使用示例
    使用妹子UI开发的体验分享
    阿里云储存代码整理(由三卷天书整理)
    测试程序的时候用到写参数或者错误日志的几个方法,用来方便发现错误
    fineUI表格控件各属性说明
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7735017.html
Copyright © 2020-2023  润新知