[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 ...
随机推荐
- 技术沙龙|京东云区块链进校园-京东云&深圳大学线下沙龙分享回顾
在刚刚结束的京东云&深圳大学技术沙龙活动中,多位京东云的技术大咖针对京东云BDS产品技术细节.开源计划,与深圳大学的同学和参会者进行了深入探讨,干货满满反响深刻,获得了在场同学与参会者的一致好 ...
- Necroptosis|Apoptosis|CTC|
大数据-外周血研究 Necroptosis与Apoptosis...区别:肿瘤导致和自身凋亡. CTC,肿瘤细胞脱落进入外周血,CTC(循环肿瘤细胞,CirculatingTumorCell)是存在于 ...
- 64位win7+PCL1.6.0+VS2010,64位win10+PCL1.6.0+VS2010
https://blog.csdn.net/liukunrs/article/details/80216329 大体转载自:https://blog.csdn.net/sinat_24206709/a ...
- iOS 蓝牙开发详解
目前iOS智能硬件的开发交互方式主要分为两种,一种是基于低功耗的蓝牙4.0技术(由于耗电低,也称作为BLE(Bluetooth Low Energy))对应iOS的框架为CoreBluetooth,另 ...
- 19 docker 多机器通信
1. 本章实验 2. 环境搭建 1.编写 Vagrantfile 并创建虚拟机 并虚拟机node1绑定外部 192.168.205.10:8888 node2绑定外部 192.168.205.10:9 ...
- 编写shell脚本,使用 nohup 让springboot 项目在后台持续运行
1.将springboot项目打成jar放在linux的某个目录下. 2.新建一个nohup.log文件. 3.使用vi命令新建一个start.sh文件并写下以下内容: #!/bin/sh nohup ...
- Python笔记_第四篇_高阶编程_高阶函数_3.sorted
1. sorted函数: 常用的排序分:冒泡排序.选择排序.快速排序.插入排序.计数器排序 实例1:普通排序 # 普通排序 list1 = [,,,,] list2 = sorted(list1) # ...
- MVPR下的PHP分页教程
这个PHP分页其实不难,现在就开始看看核心思路吧. 我习惯从最底层开始看起. 1. 首先用LIMIT偏移QUERY的指针 /* * get hot post by current page * @pa ...
- zabbix自定义邮件报警
1.启动动作 2.设定发件人邮箱 进入QQ邮箱: 通过短信验证开启如下服务,并生成授权码: 3.配置收件人
- 17.3.12----OS模块ya
1---他是一xu个python系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作. import os#导入这个os模块,其实python模块就是C元的包含很多函数的文件 2---o ...