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. WebSocket --为什么引入WebSocket协议

    Browser已经支持http协议,为什么还要开发一种新的WebSocket协议呢?我们知道http协议是一种单向的网络协议,在建立连接后,它只允许Browser/UA(UserAgent)向WebS ...

  2. java常用的空对象 null

  3. php用zendstudio建立wsdl

    首先,新建的时候要选择soap,然后deocument和rpc都可以. 类和方法的页面: <?php //发货接口 class test{ function send_do_delivery($ ...

  4. svn Can't revert without reverting children 解决方案

    EMZ3.0 qrh$ svn commit -m ""svn: E155010: Commit failed (details follow):svn: E155010: '/U ...

  5. java添加背景图片

    总结:我们通常实现添加背景图片很容易,但是再添加按钮组件就会覆盖图片.原因是: 有先后啊.setlayout();与布局有很大关系 请调试代码的时候,仔细揣摩.我晕了 还可以添加文本框,密码框 fra ...

  6. mysql存储过程获取sqlstate message_text

    群里有人询问,在mysql的proc中如何获取错误信息.错误编号呢?我们知道在oracle.mssql中比较简单: oracle中sqlcode,sqlerrm ;mssql中ERROR_PROCED ...

  7. 转:MySQL InnoDB Add Index实现调研

    MySQL InnoDB Add Index实现调研 MySQL Add Index实现 MySQL各版本,对于add Index的处理方式是不同的,主要有三种: Copy Table方式 这是Inn ...

  8. 【转】linux平台Redis安装部署

    Redis是一种高级key-value数据库.它跟memcached类似,不过数据可以持久化,而且支持的数据类型很丰富.有字符串,链表,集 合和有序集合.支持在服务器端计算集合的并,交和补集(diff ...

  9. 开发环境入门 linux基础 (部分)正则表达式 grep sed

    /etc/profile /etc/bashrc  .变量添加到shell环境中,永久生效. /root/.bashrc /root/.bash_profile 正则表达式 定义:正则就是用一些具有特 ...

  10. DVWA平台v1.9-Command Injection

    命令拼接: &:简单的拼接,第一条命令和第二条命令间没有什么制约关系 &&:第一条命令执行成功了,才会执行第二条命令 |:第一条命令的输出作为第二条命令的输入 ||:第一条命令 ...