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

  

最新文章

  1. QQ浏览器安卓5.8版本的Uint8Array API有bug
  2. Pechkin:html -&gt; pdf 利器
  3. 将xml文件作为一个小的数据库,进行学生的增删改查
  4. 【News】SpagoBI中国官方微信对外发布
  5. Memcached通用类(基于Memcached Client Library)
  6. C#遍历窗体所有控件或某类型所有控件
  7. Java8 Lambda表达应用 -- 单线程游戏server+异步数据库操作
  8. windows下 nginx php 环境搭建
  9. Erlang使用ProtoBuffer
  10. ntopng 推送solr
  11. IIS、nginx、apache只允许域名访问配置
  12. EBS系统管理常用SQL语句整理汇总(参考网上资料&amp;其他人博客)
  13. 【RL-TCPnet网络教程】第12章 TCP传输控制协议基础知识
  14. Java连接远程Mysql过程中遇到的各种问题
  15. ubuntu学习笔记
  16. JAVA实现Word(doc)文件读写
  17. Java覆盖
  18. 23.Hibernate-基础.md
  19. HashMap为什么存取效率那么高?
  20. sql:临时表和表变量

热门文章

  1. [IIS] 不能加载类型System.ServiceModel.Activation.HttpModule
  2. Python中try...except...else的用法
  3. Oracle OCM提纲
  4. Ubuntu16.04 Hadoop2.6.0伪分布式安装与启动中遇到的问题
  5. node与vue结合的前后端分离跨域问题
  6. Http服务端
  7. Oracle、SqlServer——基础知识——oracle 与 SqlServer 的区别(未完工)
  8. mysql如何开启远程连接(默认未开启,即使密码正确,仍然无法访问)
  9. select 动态添加option函数
  10. spirngmvc整合mybatis实现CRUD