最常使用的K个单词II|最常使用的K个单词II · Top K Frequent Words II
import java.util.NavigableSet;
public class TopK {
private Map words = null;
private NavigableSet topk = null;
private int k;
private Comparator myComparator = new Comparator() {
public int compare(String left, String right) {
if (left.equals(right))
return 0;
int left_count = words.get(left);
int right_count = words.get(right);
if (left_count != right_count) {
return right_count - left_count;
}
return left.compareTo(right);
}
};
public TopK(int k) {
// initialize your data structure here
this.k = k;
words = new HashMap();
topk = new TreeSet(myComparator);
}public void add(String word) {
// Write your code here
if (words.containsKey(word)) {
if (topk.contains(word))
topk.remove(word);
words.put(word, words.get(word) + 1);
} else {
words.put(word, 1);
}topk.add(word);
if (topk.size() > k) {
topk.pollLast();
}
}public List topk() {
// Write your code here
List results = new ArrayList();
Iterator it = topk.iterator();
while(it.hasNext()) {
String str = (String)it.next();
results.add(str);
}
return results;
}
【最常使用的K个单词II|最常使用的K个单词II · Top K Frequent Words II】}
推荐阅读
- 口头禅
- 《世上最美的离别》丨最辛苦的是妈妈,最被家人忽视的也是妈妈
- hexo博客主题推荐
- 前任3——那些死硬着没有开口的话到了最后就再也没有开口的机会
- Vim基础用法,最常用、最实用的命令介绍(保姆级教程)
- 世间哪种人福报最大()
- 2022年最新开课吧-孤尽训练营002期—T31购票+抢票系统
- 如何下载最新Windows10镜像文件(.iso文件)
- 案例
- 我们会再次相见,以自己最好的模样