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.
Approach #1: C++.[unordered_map]
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
if (words.empty()) return {};
unordered_map<string, int> m;
for (string word : words) {
m[word]++;
}
vector<pair<string, int>> temp(m.begin(), m.end());
sort(temp.begin(), temp.end(), cmp);
vector<string> ans;
for (int i = 0; i < k; ++i) {
ans.push_back(temp[i].first);
}
return ans;
} private:
static bool cmp(pair<string, int> a, pair<string, int> b) {
if (a.second == b.second) return a.first < b.first;
return a.second > b.second;
}
};
Approach #2: Java. [heap]
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2)->count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) ); for (String word : count.keySet()) {
heap.offer(word);
if (heap.size() > k) heap.poll();
} List<String> ans = new ArrayList();
while (!heap.isEmpty()) ans.add(heap.poll());
Collections.reverse(ans);
return ans;
}
}
Approach #3: Python.
import collections
import heapq
class Solution:
# Time Complexity = O(n + nlogk)
# Space Complexity = O(n)
def topKFrequent(self, words, k):
count = collections.Counter(words)
heap = []
for key, value in count.items():
heapq.heappush(heap, Word(value, key))
if len(heap) > k:
heapq.heappop(heap)
res = []
for _ in range(k):
res.append(heapq.heappop(heap).word)
return res[::-1] class Word:
def __init__(self, freq, word):
self.freq = freq
self.word = word def __lt__(self, other):
if self.freq == other.freq:
return self.word > other.word
return self.freq < other.freq def __eq__(self, other):
return self.freq == other.freq and self.word == other.word
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] 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 = [ ...
- [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 ...
- 347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,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 ...
随机推荐
- acm 士兵杀敌(一)
士兵杀敌(一) 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的. 小工是南将军手下的军师,南将军现在 ...
- 四川第七届 C Censor (字符串哈希)
Censor frog is now a editor to censor so-called sensitive words (敏感词). She has a long text pp. Her j ...
- C Primer Plus学习笔记(七)- 字符输入/输出和输入验证
单字符 I/O:getchar() 和 putchar() getchar() 和 putchar() 每次只处理一个字符 getchar() 和 putchar() 都不是真正的函数,它们被定义为供 ...
- Flash 零日漏洞复现(CVE-2018-4878)
项目地址:https://github.com/Sch01ar/CVE-2018-4878.git 影响版本为:Adobe Flash Player <= 28.0.0.137 攻击机器IP:1 ...
- webapi中使用token验证(JWT验证)
本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...
- pa15-三省吾身
序号 项 1 凡事提前10分钟 凡事提前10分钟,会让你有充裕的时间应对可能的突发事件,更加从容. 试着把起床闹钟提前10分钟,你就会发现你出门不必急匆匆,早饭也可慢慢享用,一整天的状态也 ...
- SQL Server——事务嵌套(未完工)
http://www.cnblogs.com/Kymo/archive/2008/05/14/1194161.html 先看一下SQL Server Online Help相关的说明 Begin Tr ...
- Oracle监听程序没法启动的一种解决办法
遇到的是监听日志多了 oracle\diag\tnslsnr\WIN-MLPKEV0JE05\listener\trace 删除 日志关闭 lsnrctl set log_status off;
- C#操作JSON专题
第一章:C#如何拿到从http上返回JSON数据? 第二章:C#如何解析JSON数据?(反序列化对象) 第三章:C#如何生成JSON字符串?(序列化对象) 第四章:C#如何生成JSON字符串提交给接口 ...
- LINUX oracle dbca无法启动
LINUX操作系统中执行DBCA无法启动 方法:执行以下命令后再执行DBCA xhost +