zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    JavaScript 数组
    Function类型
    javascript面向对象(一)
    javascript变量的作用域
    登陆验证
    注册验证
    php类
    二叉搜索树的 查询最小值
    二叉 搜索树查找最大值
    二叉搜索树 中查找是否存在该值
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7735017.html
Copyright © 2011-2022 走看看