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:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.
Follow up:
Try to solve it in O(n log k) time and O(n) extra space.

先用 hashmap 存储string 和出现次数的映射, 然后insert并维持一个size为K的priorityqueue (注意要自己定义compare 函数),最后会得到top Kth words 但是是从小到大排序,注意要reverse:

class Solution {
public List<String> topKFrequent(String[] words, int k) {
if(words == null || words.length == 0 || k <= 0){
return new ArrayList<String>();
}
Map<String, Integer> map = new HashMap<>();
PriorityQueue<Map.Entry<String,Integer>> pq = new PriorityQueue<>((e1, e2) -> compareElement(e1,e2));
for(String str : words){
map.put(str, map.getOrDefault(str, 0)+1);
}
for(Map.Entry<String,Integer> entry : map.entrySet()){
pq.add(entry);
if(pq.size() > k){
pq.poll();
}
}
List<String> res = new ArrayList<>();
while(!pq.isEmpty()){
res.add(pq.poll().getKey());
}
Collections.reverse(res);
return res;
} private int compareElement(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2){
if(e1.getValue() - e2.getValue() != 0)
{return e1.getValue() - e2.getValue();}
else
{return e2.getKey().compareTo(e1.getKey());}
}
}

  

LeetCode - Top K Frequent Words的更多相关文章

  1. [LeetCode] Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  2. [LeetCode] Top K Frequent Words 前K个高频词

    Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...

  3. LeetCode "Top K Frequent Elements"

    A typical solution is heap based - "top K". Complexity is O(nlgk). typedef pair<int, un ...

  4. Top K Frequent Elements 前K个高频元素

    Top K Frequent Elements 347. Top K Frequent Elements [LeetCode] Top K Frequent Elements 前K个高频元素

  5. C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  6. [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 b ...

  7. [leetcode]347. Top K Frequent Elements K个最常见元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  8. [LeetCode] 347. Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  9. 【LeetCode】692. Top K Frequent Words 解题报告(Python)

    [LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...

随机推荐

  1. UVa 3602 - DNA Consensus String 水题 难度: 0

    题目 https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_pr ...

  2. day18-python的正则表达式

    1. 正则表达式基础 1.1. 简单介绍 正则表达式并不是Python的一部分.正则表达式是用于处理字符串的强大工具,拥有自己独特的语法以及一个独立的处理引擎,效率上可能不如str自带的方法,但功能十 ...

  3. mysql存储过程中使用游标

    用户变量一般以@开头,作用于全局范围 局部变量需用 declare 定义格式为 declare 变量名 数据类型 [default value]; mysql 数据类型有 int ,float,dat ...

  4. oracle sequence

    代码块 方法一: (1)删除序列; (2)重新创建: 这个方法比较简单粗暴. drop sequence sequence_name; create sequence sequence_name mi ...

  5. shell脚本实例-实现监控tcp的链接状态另一种方式批量创建用户

    Array实现TCP的链接状态 #!/usr/bin/bash declare -A status type=`ss -an | grep :80|awk '{print $2}'` for i in ...

  6. JAVA测试编程

    本周我们上JAVA课的时候进行了一次测试,本次测试以模拟中国工商银行自助机ATM的功能为大致要求,要求我们进行编写调试,以求达到试题要求. 测试要求我们能模拟ATM的功能设计,当用户插卡后显示,输入密 ...

  7. Python 属性

    class Person: def __init__(self, name, gender, birth): self.name = name self.gender = gender self.bi ...

  8. python 基础5 初级函数

    函数最重要的目的是方便我们重复使用相同的一段程序.将一些操作隶属于一个函数,以后你想实现相同的操作的时候,只用调用函数名就可以,而不需要重复敲所有的语句. def my_len(): def 关键字 ...

  9. ubuntu: firefox+flashplay

    更新两步: 1.安装firefox:rm-->下载-->mv-->ln http://www.cnblogs.com/yzsatcnblogs/p/4266985.html 2. f ...

  10. 【leeetcode】125-Valid Palindrome

    problem 125. Valid Palindrome 参考 1. Leetcode_Valid Palindrome; 完