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. 吴裕雄--天生自然TensorFlow2教程:前向传播(张量)- 实战

    手写数字识别流程 MNIST手写数字集7000*10张图片 60k张图片训练,10k张图片测试 每张图片是28*28,如果是彩色图片是28*28*3-255表示图片的灰度值,0表示纯白,255表示纯黑 ...

  2. 解决 springweb Filter 读取request body miss body

    package com.lb.demo.listener; import java.io.BufferedReader; import java.io.ByteArrayInputStream; im ...

  3. IO流的学习以及统计次数最多的单词

    IO流: 处理数据类型:字节流(InputStream  OutputStream)和字节流(Reader  Writer) 数据流向不同:输入流和输出流(FileInputStream   File ...

  4. Window Jdk配置(win7/win10都可以)

    在计算机-右键属性-高级系统设置-环境标量-系统变量下进行如下配置: 1.新建->变量名:JAVA_HOME变量值:D:\Java\jdk1.6.0_12(这只是我的JDK安装路径) 2.编辑- ...

  5. 微信小程序官方示例 官方weui-wxss下载于安装 详解

    1.小程序示例源码:https://github.com/wechat-miniprogram/miniprogram-demo 2.微信 weui下载地址:https://github.com/we ...

  6. Spring Cloud Alibaba 教程 | Nacos(六)

    集群模式部署 前面我们已经学习了Nacos作为注册中心.配置中心的相关功能,但是我们之前启动Nacos是通过单实例模式启动的,只适合在学习和开发阶段,生产环境需要保证Nacos的高可用,所以今天我们来 ...

  7. Spring Cloud Alibaba 教程 | Nacos(五)

    扩展配置(extended configurations) 通过之前的学习,我们知道应用引入nacos配置中心之后默认将会加载Data ID= ${prefix} - ${spring.profile ...

  8. 1.Redis简介/配置文件

    redis简介 redis使用入门 redis安装 http://www.runoob.com/redis/redis-install.html [root@yz---- bin]# ll total ...

  9. PAT Advanced 1127 ZigZagging on a Tree (30) [中序后序建树,层序遍历]

    题目 Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree c ...

  10. PAT Advanced 1084 Broken Keyboard (20) [Hash散列]

    题目 On a broken keyboard, some of the keys are worn out. So when you type some sentences, the charact ...