【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:

  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.

题目大意

对单词按出现的次数进行排序,如果次数相同,则按照字母序排列,只返回前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)的更多相关文章

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

  2. 【LeetCode】347. Top K Frequent Elements 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 解题方法 字典 优先级队列 日期 题目地址:https://l ...

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

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

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

  6. [leetcode]347. Top K Frequent Elements K个最常见元素

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

  7. C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  8. [LeetCode] 347. Top K Frequent Elements 前K个高频元素

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

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

随机推荐

  1. sersync+rsync进行数据同步

    一:环境 操作系统环境:redhat6.6 内核版本:2.6.32-358.el6.x86_64 rsync server:192.168.2.3(部署rsync server) rsync clie ...

  2. hadoop运行jar包报错

    执行命令:[root@hadoop102 mapreduce]# hadoop jar mapreduce2_maven.jar Filter 错误信息:Exception in thread &qu ...

  3. 日常Java 2021/10/28

    Java lterator Java lterator(迭代器)不是一个集合,它是一种用于访问集合的方法,可用于迭代 ArrayList和HashSet等集合.lterator是Java迭代器最简单的 ...

  4. Spark(二)【sc.textfile的分区策略源码分析】

    sparkcontext.textFile()返回的是HadoopRDD! 关于HadoopRDD的官方介绍,使用的是旧版的hadoop api ctrl+F12搜索 HadoopRDD的getPar ...

  5. 零基础学习java------29---------网络日志数据session案例,runtime(导出jar程序)

    一. 网络日志数据session案例 部分数据 数据中的字段分别为: 访客ip地址,访客访问时间,访客请求的url及协议,网站响应码,网站返回数据量,访客的referral url,访客的客户端操作系 ...

  6. 分配器——allocators

    任何容器的构建都离不开分配器,分配器顾名思义就是分割配置内存资源的组件,分配器的效率直接影响力容器的效率. operator new()和malloc() C/C++底层都是通过malloc()调用系 ...

  7. 使用Rapidxml重建xml树

    需求 : 重建一棵xml树, 在重建过程中对原来的标签进行一定的修改. 具体修改部分就不给出了, 这里只提供重建部分的代码 code : /****************************** ...

  8. Docker 生产环境之配置容器 - 自动启动容器

    原文地址 Docker 提供了重启策略,以控制容器在退出时是否自动启动,或在 Docker 重新启动时自动启动.重启策略可确保链接的容器以正确的顺序启动.Docker 建议使用重启策略,并避免使用流程 ...

  9. 回溯——51. N皇后

    这一题在我刚开始拿到的时候,是一点思路都没有的,只能先分析题目的要求,即queen之间的规则: 不能同行 不能同列 不能同斜线 不能同左斜 不能同右斜 同时发现,在寻找所有可能结果的穷举过程中,传入的 ...

  10. vivo浏览器的快速开发平台实践-总览篇

    一.什么是快速开发平台 快速开发平台,顾名思义就是可以使得开发更为快速的开发平台,是提高团队开发效率的生产力工具.近一两年,国内很多公司越来越注重研发效能的度量和提升,基于软件开发的特点,覆盖管理和优 ...