[LC] 692. Top K Frequent Words
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.
import collections
import heapq class Element(object):
def __init__(self, word, freq):
self.word = word
self.freq = freq def __lt__(self, other):
if self.freq != other.freq:
return self.freq < other.freq
return other.word < self.word class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
my_dict = {}
for word in words:
if word in my_dict:
my_dict[word] += 1
else:
my_dict[word] = 1 freqs = []
for word, count in my_dict.items():
heapq.heappush(freqs, (Element(word, count)))
if len(freqs) > k:
heapq.heappop(freqs)
res = []
for _ in range(k):
res.append(heapq.heappop(freqs).word)
res.reverse()
return res
Solution 2:
O(klogN)
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> map = new HashMap<>();
for (String s: words) {
map.put(s, map.getOrDefault(s, 0) + 1);
}
// keep a top frequency heap
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b) ->
a.getValue() == b.getValue() ? a.getKey().compareTo(b.getKey()): b.getValue() - a.getValue()
);
pq.addAll(map.entrySet());
List<String> res = new ArrayList<>();
int i = 0;
while (i < k) {
res.add(pq.poll().getKey());
i += 1;
}
return res;
}
}
[LC] 692. Top K Frequent Words的更多相关文章
- 【LeetCode】692. Top K Frequent Words 解题报告(Python)
[LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...
- [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 ...
- #Leetcode# 692. Top K Frequent Words
https://leetcode.com/problems/top-k-frequent-words/ Given a non-empty list of words, return the k mo ...
- [LC] 347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- 692. Top K Frequent Words
Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...
- [leetcode]692. Top K Frequent Words频率最高的前K个单词
这个题的排序是用的PriorityQueue实现自动排列,优先队列用的是堆排序,堆排序请看:http://www.cnblogs.com/stAr-1/p/7569706.html 自定义了优先队列的 ...
- [leetcode]347. Top K Frequent Elements K个最常见元素
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- 最高频的K个单词 · Top K Frequent Words
[抄题]: 给一个单词列表,求出这个列表中出现频次最高的K个单词. [思维问题]: 以为已经放进pq里就不能改了.其实可以改,利用每次取出的都是顶上的最小值就行了.(性质) 不知道怎么处理k个之外的数 ...
- [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 ...
随机推荐
- 使用Map,统计字符串中每个字符出现的次数
package seday13; import java.util.HashMap; import java.util.Map; /** * @author xingsir * 统计字符串中每个字符出 ...
- aliyun二级域名绑定
NameVirtualHost *:80 开启监听 <VirtualHost *:80> DocumentRoot /home/service/ ServerName serv ...
- (转载)Tomcat 报错 (The tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config is mi)
错误如图所示: 目前对于这个错误的原因尚不清楚,目前只知道如何解决这个错误,等到以后知道了原因之后再更改此文. 原因猜测: 之前你的eclipse关联的tomcat由于某种原因出现了信息丢失,需要重新 ...
- 吴裕雄--天生自然ShellX学习笔记:Shell 输入/输出重定向
大多数 UNIX 系统命令从你的终端接受输入并将所产生的输出发送回到您的终端.一个命令通常从一个叫标准输入的地方读取输入,默认情况下,这恰好是你的终端.同样,一个命令通常将其输出写入到标准输出,默 ...
- malloc 底层实现及原理
摘要:偶尔看到面试题会问到 malloc 的底层原理,今天就来记录一下,毕竟学习要“知其所以然”,这样才会胸有成竹. 注:下面分析均是基于 linux 环境下的 malloc 实现.步骤是:先总结结论 ...
- ES6 find()
Array.prototype.find() 返回数组中满足提供测试函数的第一个元素的值,否则返回undefined let b = blogs.find(function(e) => { re ...
- 第二季第十天 es6新特性新特性
1.set的应用(去重)js标准内置对象 适用范围:String,Array(数字基本数据类型不可以) set的方法:例子 var s = new Set(data) 增加: s.add(data) ...
- ZJNU 2204 - dzj的数学作业
我猜这个数列可以直接从大到小凑…… 推出帕多瓦数列每一项,从大到小循环 遇到小于等于x的项就减掉这一项 全部循环完毕后判断x是否为0即可 #include<stdio.h> typedef ...
- 电影评论分类:二分类问题(IMDB数据集)
IMDB数据集是Keras内部集成的,初次导入需要下载一下,之后就可以直接用了. IMDB数据集包含来自互联网的50000条严重两极分化的评论,该数据被分为用于训练的25000条评论和用于测试的250 ...
- MySQL--MySQL 日志
在 MySQL中,有 4 种不同的日志,分别是错误日志.二进制日志(BINLOG 日志).查询日志和慢查询日志. 1.错误日志 错误日志是 MySQL 中最重要的日志之一,它记录了当 mysqld 启 ...