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.

Approach #1: C++.[unordered_map]

class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
if (words.empty()) return {};
unordered_map<string, int> m;
for (string word : words) {
m[word]++;
}
vector<pair<string, int>> temp(m.begin(), m.end());
sort(temp.begin(), temp.end(), cmp);
vector<string> ans;
for (int i = 0; i < k; ++i) {
ans.push_back(temp[i].first);
}
return ans;
} private:
static bool cmp(pair<string, int> a, pair<string, int> b) {
if (a.second == b.second) return a.first < b.first;
return a.second > b.second;
}
};

  

Approach #2: Java. [heap]

class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2)->count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) ); for (String word : count.keySet()) {
heap.offer(word);
if (heap.size() > k) heap.poll();
} List<String> ans = new ArrayList();
while (!heap.isEmpty()) ans.add(heap.poll());
Collections.reverse(ans);
return ans;
}
}

  

Approach #3: Python.

import collections
import heapq
class Solution:
# Time Complexity = O(n + nlogk)
# Space Complexity = O(n)
def topKFrequent(self, words, k):
count = collections.Counter(words)
heap = []
for key, value in count.items():
heapq.heappush(heap, Word(value, key))
if len(heap) > k:
heapq.heappop(heap)
res = []
for _ in range(k):
res.append(heapq.heappop(heap).word)
return res[::-1] class Word:
def __init__(self, freq, word):
self.freq = freq
self.word = word def __lt__(self, other):
if self.freq == other.freq:
return self.word > other.word
return self.freq < other.freq def __eq__(self, other):
return self.freq == other.freq and self.word == other.word

  

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] 692. Top K Frequent Words

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

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

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

  9. [LeetCode] Top K Frequent Words 前K个高频词

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

随机推荐

  1. Azure上每个VM多个IP地址

    Azure的每个VM都有多种IP地址,包括DIP.VIP和PIP.具体如下: DIP地址是在VM里能够看到的IP地址,即私网地址:PIP地址是这个VM关联的公网IP地址,即公网地址:VIP地址是负载均 ...

  2. laravel csrf保护

    有时候我们的项目需要和外部的项目进行接口对接,如果是post的方式请求;laravel要求csrf保护 但是别人是ci框架或者没有csrf_token的;该如何处理呢? 可以把我们不需要csrf的ur ...

  3. web聊天相关知识

    http相关知识 http是无状态,请求,响应模式的通信模式,就是用户每次通过浏览器点击一下页面,都需要重新与web服务器建立一下连接,且发送自己的 session id 给服务器端以使服务器端验证此 ...

  4. Disconf web管理端安装

    1.环境配置配置java.maven环境,并安装mysql,reids,zookeeeper,Nginx2.下载disconf下载https://codeload.github.com/knightl ...

  5. 查看,修改ceph节点的ceph配置命令

    标签(空格分隔): ceph,ceph运维,ceph配置 查看ceph配置 1. 查看ceph默认配置: # ceph --show-config 2. 查看 type.num 的ceph默认配置: ...

  6. Oracle 多表查询(2)

    四.统计函数及分组查询 1.统计函数 在之前学习过一个COUNT()函数,此函数的功能可以统计出表中的数据量,实际上这个就是一个统计函数,而常用的统计函数有如下几个: COUNT():查询表中的数据记 ...

  7. VUE简单入门

    Vue.js是当下很火的一个JavaScript MVVM库,它是以数据驱动和组件化的思想构建的.相比于Angular.js,Vue.js提供了更加简洁.更易于理解的API,使得我们能够快速地上手并使 ...

  8. oracle时间段查询-从00:00:00开始

    之所以记录一下这篇博文,是因为前段时间搞的一个查询发现要从00:00:00这个时间段开始,必须要通过拼接字符串. <select id="queryApplyProgressList& ...

  9. JAVA基础知识总结13(同步)

    好处:解决了线程安全问题. 弊端:相对降低性能,因为判断锁需要消耗资源,还容易产生了死锁. 定义同步是有前提的: 1,必须要有两个或者两个以上的线程,才需要同步. 2,多个线程必须保证使用的是同一个锁 ...

  10. sql基本查询语句练习

    student(S#,Sname,Sage,Ssex) 学生表       S#:学号: Sname:学生姓名:Sage:学生年龄:Ssex:学生性别 Course(C#,Cname,T#) 课程表 ...