【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 ...
随机推荐
- js变量作为数组对象的键值方法
js变量作为数组对象的键值方法,变量键值获取数组值 js也可以像php的数组一样用下标获取数组的值,方法是: var arr = {'key':'abc'}; var key = 'key'; con ...
- A Child's History of England.45
To forgive these unworthy princes was only to afford them breathing-time for new faithlessness. They ...
- 零基础学习java------day17------缓冲字节流,转换字节流,简化流,缓冲字符流,序列化和对象流
1. 缓冲字节流 缓冲区:缓冲区实质上是一个数组.通常它是一个字节数组,但是也可以使用其他种类的数组.但是一个缓冲区不 仅仅 是一个数组.缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/写进程 ...
- 【leetcode】122.Best Time to Buy and Sell Stock II(股票问题)
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. ...
- ORACLE 数据块PCTFREE和PCTUSED
PCTFREE表示一个数据块可用空间小于PCTFREE时,该数据块不在被记录在FREELIST中,即不能插入新数据. PCTUSED表示一个数据块已经用空间如果小于PCTUSED时,该数据块才会被重新 ...
- 设置linux下oracle开机自启动
1.修改配置文件,vi /etc/oratab orcl:/u01/app/oracle/product/11.2.0/db_1:Y 2.创建启动文件,/etc/init.d/ #!/bin/sh # ...
- MySQL 用户权限相关命令
##1.创建用户: create user test identified by '123456';##identified后面跟密码 ##2.查询所有用户: select user from mys ...
- web端 - 返回上一步,点击返回,跳转上个页面 JS
1.方法一: <script language="javascript" type="text/javascript"> window.locati ...
- 利用代码覆盖率提高嵌入式软件的可靠性 - VectorCAST
简介 代码覆盖率是衡量软件测试完成情况的指标,通常基于测试过程中已检查的程序源代码比例 计算得出.代码覆盖率可以有效避免包含未测试代码的程序被发布. 代码覆盖率能不能提高软件的可靠性?答案是肯定的,代 ...
- Set数据结构基本介绍
构造 const set = new Set([1, 2, 3, 4, 4]); 可接受的参数为所有具有iterable 接口的数据 特性: 类似数组,无重复值. const set = new Se ...