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.

  • 相关阅读:
    原生内存泄漏检测
    安卓适配
    游戏里的动态阴影-ShadowMap实现原理
    游戏里的跨地图寻路算法
    Unity-Shader-动态阴影(上) 投影的矩阵变换过程
    Unity-奥义技能背景变黑效果
    UGUI学习笔记
    Unity-Shader-镜面高光Phong&BlinnPhong-油腻的师姐在哪里
    Unity-Shader-光照模型之漫反射
    Unity3D-Shader-热扭曲效果
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7735017.html
Copyright © 2011-2022 走看看