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:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

Follow up:

  1. 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的更多相关文章

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

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

  2. [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 ...

  3. #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 ...

  4. [LC] 347. Top K Frequent Elements

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

  5. 692. Top K Frequent Words

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

  6. [leetcode]692. Top K Frequent Words频率最高的前K个单词

    这个题的排序是用的PriorityQueue实现自动排列,优先队列用的是堆排序,堆排序请看:http://www.cnblogs.com/stAr-1/p/7569706.html 自定义了优先队列的 ...

  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. 最高频的K个单词 · Top K Frequent Words

    [抄题]: 给一个单词列表,求出这个列表中出现频次最高的K个单词. [思维问题]: 以为已经放进pq里就不能改了.其实可以改,利用每次取出的都是顶上的最小值就行了.(性质) 不知道怎么处理k个之外的数 ...

  9. [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 ...

随机推荐

  1. swoole怎么连接数据库

    异步连接到MySQL服务器. $serverConfig为MySQL服务器的配置,必须为关联索引数组 $callback连接完成后回调此函数 swoole连接数据库实例: 推荐学习:swoole教程 ...

  2. CSS padidng-top\margin-top\fixed 的特殊性

    参考: 使用css时,可能会出错的两个地方 1.padidng-top\margin-top padidng-top\margin-top可以设置'px' 或者是'%',设置'px'略过,说一下设置‘ ...

  3. 干货 | DRDS 与TiDB浅析

    干货 | DRDS 与TiDB浅析 北京it爷们儿 京东云开发者社区  4月17日 在谈论数据库架构和数据库优化的时候,会常听到"分库分表"."分片".&quo ...

  4. 201709-1 打酱油 Java

    思路: 先看能不能买5瓶,因为送的最多,然后看能不能买3瓶,最后一瓶一瓶地买 import java.util.Scanner; public class Main { public static v ...

  5. sqlserver2008的sql语句支持的最大长度

    想写一个sql语句,很长,主要是in后跟着无数个用户ID,(虽然实现方式很低级,但是还是凑合着用吧) 不知道sql最大长度是多少,看了 SQL Server 的最大容量规范,写的是 包含 SQL 语句 ...

  6. unity学习 5.x依赖打包和解包

    unity5已经封装好了接口,所以依赖打包并没有那么神秘和复杂了. 打包: 1.定义好资源的assetBundleName 2.BuildPipeline.BuildAssetBundles,指定资源 ...

  7. JS - ES5与ES6面向对象编程

    1.面向对象 1.1 两大编程思想 1.2 面向过程编程 POP(Process-oriented programming) 1.3 面向对象编程 OOP (Object Oriented Progr ...

  8. Python笔记_第一篇_面向过程_第一部分_8.画图工具(小海龟turtle)

    turtle 是一个简单的绘图工具. 提供一个小海龟,可以把它理解为一个机器人,只能听懂有限的命令,且绘图窗口的原点(0,0)在中间,默认海龟的方向是右侧海龟的命令包括三类:运动命令.笔画控制命令.其 ...

  9. Ubuntu目錄

    /         (这就是著名的根)├── bin         (你在终端运行的大多数程序,比如cp.mv...)├── boot         (内核放在这里,这个目录也经常被作为某个独立分 ...

  10. 【收藏】每天更新!全网热门公共BT种子 BitTorrent Tracker 列表合集

    每天更新!全网热门公共 BitTorrent Tracker 列表合集. 该项目仅将全网热门的公共 Tracker 列表制作成合集方便大家使用,无需再一个个导入了~. 「English」(tracke ...