【LeetCode】692. Top K Frequent Words 解题报告(Python)
【LeetCode】692. Top K Frequent Words 解题报告(Python)
标签: LeetCode
题目地址:https://leetcode.com/problems/top-k-frequent-words/description/
题目描述:
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:
1. Try to solve it in O(n log k) time and O(n) extra space.
题目大意
对单词按出现的次数进行排序,如果次数相同,则按照字母序排列,只返回前k个。
解题方法
既然看到出现次数,那么那么一般都是使用自带的Counter进行统计的。按出现次数排序这个可以使用most_common()函数,但是这个函数对出现次数相等时不是按照字母序排列的。所以需要自定义排序函数。
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
count = collections.Counter(words)
def compare(x, y):
if x[1] == y[1]:
return cmp(x[0], y[0])
else:
return -cmp(x[1], y[1])
return [x[0] for x in sorted(count.items(), cmp = compare)[:k]]
另外一种方法也是排序:
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
count = collections.Counter(words)
candidates = count.keys()
candidates.sort(key = lambda w: (-count[w], w))
return candidates[:k]
重要的来了,一般,我们认为找出k个最大最小的问题都是一个使用堆来做的。这个题中,学习了python的堆的用法。
heapq.heapify(heap)
能在线性时间内,把一个列表转成堆。
heapq.heappop(heap)
能直接弹出堆的堆顶。
heappush(heap,5)
向堆中添加元素。
注意,heap是个list,哪怕使用了上述函数之后,这个仍然是list.
python中的堆默认是小根堆,如果想使用大根堆,在添加元素的时候使用负号即可。
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
count = collections.Counter(words)
heap = [(-freq, word) for word, freq in count.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)]
日期
2018 年 3 月 14 日
【LeetCode】692. Top K Frequent Words 解题报告(Python)的更多相关文章
- [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】347. Top K Frequent Elements 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 解题方法 字典 优先级队列 日期 题目地址:https://l ...
- #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 ...
- [LeetCode] 347. Top K Frequent Elements 解题思路 - Java
Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...
- [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 = [ ...
- C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解
版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...
- [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 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 ...
随机推荐
- 42-Remove Nth Node From End of List
Remove Nth Node From End of List My Submissions QuestionEditorial Solution Total Accepted: 106592 To ...
- UE4之Slate: SImage
概述 距离上次记录<UE4之Slate:纯C++工程配置>后已经好长时间了: 这个随笔来记录并分享一下SImage控件的使用,以在屏幕上显示一张图片: 目标 通过SImage控件的展示,学 ...
- 基于 Golang 构建高可扩展的云原生 PaaS(附 PPT 下载)
作者|刘浩杨 来源|尔达 Erda 公众号 本文整理自刘浩杨在 GopherChina 2021 北京站主会场的演讲,微信添加:Erda202106,联系小助手即可获取讲师 PPT. 前言 当今时 ...
- A Child's History of England.46
As, one hundred years before, the servile [卑躬屈膝的~serve] followers of the Court had abandoned the Con ...
- 数组的高阶方法map filter reduce的使用
数组中常用的高阶方法: foreach map filter reduce some every 在这些方法中都是对数组中每一个元素进行遍历操作,只有foreach是没有 ...
- 【AWS】【Basis】基础概念
1.基础服务类型: 1.1. 链接: 官方文档,很详细:https://www.amazonaws.cn/products/#compute_networking/?nc1=f_dr 这个是一个whi ...
- Redis,Memcache,MongoDb的特点与区别
Redis Redis 简介 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点: Redis支 ...
- SSO(单点登录)示例
此文为转载文章,出处:https://www.cnblogs.com/jpfss/p/9273680.html SSO在我们的应用中非常常见,例如我们在OA系统登录了,我们就可以直接进入采购系统,不需 ...
- Java RestTemplate传递参数
最近使用Spring 的 RestTemplate 工具类请求接口的时候发现参数传递的一个坑,也就是当我们把参数封装在Map里面的时候,Map 的类型选择. 使用RestTemplate post请求 ...
- Java Log4j 配置文件
### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.lo ...