题目描述:
解:
先用Map统计词频,然后放入集合类按需排序取前k个即可。
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String,Integer> map = new HashMap<String, Integer>();
for(String word : words) {
map.put(word,map.getOrDefault(word,0)+1);
}
List<String> ret = new ArrayList<String>();
for(Map.Entry<String, Integer> entry : map.entrySet()) {
ret.add(entry.getKey());
}
Collections.sort(ret,(word1,word2) -> {
return map.get(word1) == map.get(word2) ? word1.compareTo(word2) : map.get(word2) - map.get(word1);
});
return ret.subList(0,k);
}
}
进阶:
小根堆优化
public class Solution {
public List<String> topKFrequent(String[] words, int k) {
// 1.先用哈希表统计单词出现的频率
Map<String, Integer> count = new HashMap();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
// 2.构建小根堆 这里需要自己构建比较规则 此处为 lambda 写法 Java 的优先队列默认实现就是小根堆
PriorityQueue<String> minHeap = new PriorityQueue<>((s1, s2) -> {
if (count.get(s1).equals(count.get(s2))) {
return s2.compareTo(s1);
} else {
return count.get(s1) - count.get(s2);
}
});
// 3.依次向堆加入元素。
for (String s : count.keySet()) {
minHeap.offer(s);
// 当堆中元素个数大于 k 个的时候,需要弹出堆顶最小的元素。
if (minHeap.size() > k) {
minHeap.poll();
}
}
// 4.依次弹出堆中的 K 个元素,放入结果集合中。
List<String> res = new ArrayList<String>(k);
while (minHeap.size() > 0) {
res.add(minHeap.poll());
}
// 5.注意最后需要反转元素的顺序。
Collections.reverse(res);
return res;
}
}
作者:qi-ye-jun
链接:https://leetcode-cn.com/problems/top-k-frequent-words/solution/xiao-gen-dui-huo-zhe-hashbiao-pai-xu-by-9uj06/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。