692. Top K Frequent Words
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:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Input words contain only lowercase letters.
Follow up:
- 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的更多相关文章
- 【LeetCode】692. Top K Frequent Words 解题报告(Python)
[LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...
- [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 ...
- #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 ...
- [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 ...
- [leetcode]692. Top K Frequent Words频率最高的前K个单词
这个题的排序是用的PriorityQueue实现自动排列,优先队列用的是堆排序,堆排序请看:http://www.cnblogs.com/stAr-1/p/7569706.html 自定义了优先队列的 ...
- [leetcode]347. Top K Frequent Elements K个最常见元素
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- [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 ...
- 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 ...
- [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 ...
随机推荐
- unix下网络编程之I/O复用(四)
首先需要了解的是select函数: select函数 #include<sys/select.h> #include<sys/time.h> int select (int m ...
- maven用途、核心概念、用法、常用参数和命令、扩展
设置问题解决. http://trinea.iteye.com/blog/1290898 本文由浅入深,主要介绍maven的用途.核心概念(Pom.Repositories.Artifact.Buil ...
- Linux应用程序调用其他程序执行
一.system 1.作用 在Linux应用程序中调用另一个程序: 2.用法 system("/sbin/ifconfig"): 二.popen 1.作用 调用另一个程序执行,同时 ...
- filter中获取spring bean
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...
- spring学习六
1: @Valid 注解 @NotNull(message="名字不能为空") private String userName; @Max(value=120,message ...
- [置顶]
strcpy()与strncpy()的区别
头文件:#include <string.h> strcpy() 函数用来复制字符串,其原型为: char *strcpy(char *dest, const char *src); [参 ...
- Python函数(一)-return返回值
定义一个函数可以在最后加上return返回值,方便查看函数是否运行完成和返回函数的值 # -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR&qu ...
- centos6 安装teamviewer
wget http://www.teamviewer.com/download/teamviewer_linux.rpm yum -y install temviewerX.rpm 机器最好联网,能够 ...
- App启动原理和启动过程
一.程序启动原理 1.1.main函数中执行了一个UIApplicationMain这个函数UIApplicationMain(int argc, char *argv[], NSString ...
- C获取当前时间
#include <stdio.h> #include <time.h> #include <string> #include <windows.h> ...