题目
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: [“i”, “love”, “leetcode”, “i”, “love”, “coding”], k = 2
输出: [“i”, “love”]
解析: “i” 和 “love” 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 “i” 在 “love” 之前。
示例 2:
输入: [“the”, “day”, “is”, “sunny”, “the”, “the”, “the”, “sunny”, “is”, “is”], k = 4
输出: [“the”, “is”, “sunny”, “day”]
解析: “the”, “is”, “sunny” 和 “day” 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
1.hashmap+桶排序
import java.util.*;
class Solution {
public List<String> topKFrequent(String[] words, int k) {
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()){
int fre = map.get(key);
if(buckets[fre]==null){
buckets[fre]=new ArrayList<>();
}
buckets[fre].add(key);
}
List<String> topk = new ArrayList<>();
for(int i=buckets.length-1;i>=0&&topk.size()<k;i--){
if(buckets[i]==null){
continue;
}
//对每个桶内具有相同频率的单词进行按照字母排序
Collections.sort(buckets[i]);
if(buckets[i].size()<=(k-topk.size())){
topk.addAll(buckets[i]);
}else{
topk.addAll(buckets[i].subList(0,k-topk.size()));
}
}
return topk;
}
}
2.hashmap+priorityQueue
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;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/top-k-frequent-words/solution/qian-kge-gao-pin-dan-ci-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String, Integer> map = new HashMap<>();
for (String word : words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> queue = new PriorityQueue<>(k, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (map.get(s1).equals(map.get(s2))) {
return s2.compareTo(s1);
}
return map.get(s1).compareTo(map.get(s2));
}
});
for (String key : map.keySet()) {
if (queue.size() < k) {
queue.add(key);
} else if (queue.comparator().compare(key, queue.peek()) > 0) {
queue.poll();
queue.add(key);
}
}
String[] res = new String[k];
for (int i = k - 1; i >= 0; i--) {
res[i] = queue.poll();
}
return Arrays.asList(res);
}
}
作者:reals
链接:https://leetcode-cn.com/problems/top-k-frequent-words/solution/shi-yong-zui-xiao-dui-shi-xian-javazhong-de-you-xi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。