题目地址
https://leetcode.com/problems/top-k-frequent-words/
题目描述
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.
思路
- 方法1, bucket sort.
- 方法2, hashmap加sort.
- 方法3, hashmap加priority queue.
关键点
代码
- 语言支持:Java
// bucket sort
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> res = new ArrayList<>();
if (words == null || words.length == 0) {
return res;
}
Map<String, Integer> map = new HashMap<>();
for (String word: words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
List<String>[] buckets = new ArrayList[words.length + 1];
for (String key: map.keySet()) {
if (buckets[map.get(key)] == null) {
buckets[map.get(key)] = new ArrayList<>();
}
buckets[map.get(key)].add(key);
}
for (int i = buckets.length - 1; i >= 0; i--) {
if (buckets[i] == null) {
continue;
}
Collections.sort(buckets[i]);
for (String str: buckets[i]) {
if (res.size() == k) {
return res;
}
res.add(str);
}
}
return res;
}
}
// map + sort
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> res = new ArrayList<>();
if (words == null || words.length < k) {
return res;
}
Map<String, Integer> map = new HashMap<>();
for (String str: words) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
res.addAll(map.keySet());
Collections.sort(res, (a, b) -> {
if (map.get(a) == map.get(b)) {
return a.compareTo(b);
} else {
return map.get(b) - map.get(a);
}
});
return res.subList(0, k);
}
}
// hashmap + PQ
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> res = new ArrayList<>();
if (words == null || words.length < k) {
return res;
}
Map<String, Integer> map = new HashMap<>();
for (String str: words) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
(a, b) -> {
if (a.getValue() == b.getValue()) {
return a.getKey().compareTo(b.getKey());
} else {
return b.getValue() - a.getValue();
}
}
);
for (Map.Entry<String, Integer> entry: map.entrySet()) {
pq.offer(entry);
}
for (int i = 0; i < k; i++) {
res.add(pq.poll().getKey());
}
return res;
}
}
网友评论