[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 ...
随机推荐
- c语言中指向整型指针的指针的理解
/************************************************************************* > File Name: ptr_ptr_i ...
- svnkit-常用api
0.功能列表 svnkit功能列表 1.递归获取指定目录下目录和文件,以树形展示[svn Update] 2.获取指定文件和属性(版本号.作者.日期.文件类型) 3.获取指定文件或目录的历史记录(版本 ...
- CodeForces - 350B(反向建图,)
B - Resort CodeForces - 350B B. Resort time limit per test 2 seconds memory limit per test 256 megab ...
- 神经网络 参数计算--直接解析CKPT文件读取
1.tensorflow的模型文件ckpt参数获取 import tensoflow as tf from tensorflow.python import pywrap_tensorflow mod ...
- share团队冲刺2
团队冲刺第二天 昨天:在网上学习app开发的简单操作代码,实现了简单的输出界面,学会了添加按钮控件. 今天:继续昨天的进度,先进行登陆界面窗口的制作. 问题:目前只能在activity添加简单代码,复 ...
- 实体机安装Ubuntu系统
今天windows突然蓝屏了,索性安装个 Ubuntu 吧,这次就总结一下实体机安装 Ubuntu 的具体步骤 note: 本人实体机为笔记本 型号为:小米pro U盘为金士顿:8G 安装系统:Ubu ...
- Codeforces Round #555 (Div. 3) B. Long Number 【仔细读题】
B. Long Number time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- 用c语言实现的几个小项目
1.参考:Linux系统编程 2.参考:制作简单计算器 3.参考:制作2048小游戏 4.参考:五子棋实现
- UML-为什么要使用层?
1.内聚职责:使关系分离.减少耦合和依赖,提高潜在复用性. 2.领域层和技术服务层可以是分布式的 3.利于团队开发
- Java clone方法的使用
浅克隆 Person p2 = (Person) p1.clone(); clone()方法使用后得到p2,p2和p1指向不同的地址.但是如果p1中的属性是引用类型,那么不再对这个引用类型进行复制,而 ...