由于缺少更好的名称,我将调用我正在寻找的数据结构作为“TopScoreMap”。
这是要求。首先,地图的大小是固定的。例如,地图只需要保留将在此地图上抛出的前n个条目。在密钥方面排名前n位。由于地图应按其键排序,因此我选择基于java.util.TreeMap
实施此地图。以下是我实施的内容。这已经通过了一些测试用例。我的问题是:
是否存在提供此功能的现有数据结构?
- 醇>
如果没有,有没有办法在执行
put
时避免迭代?看起来像O(n ^ 2),最坏的情况。
class TopScoreMap {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
int max = 0;
public TopScoreMap() {
this(5);
}
public TopScoreMap(int maxCapacity) {
this.max = maxCapacity;
}
public void put(int score, String player) {
if (map.size() < max) {
map.put(score, player);
}
else {
Iterator<Integer> it = map.keySet().iterator();
while (it.hasNext()) {
int currentKey = it.next();
if (currentKey < score) {
map.remove(currentKey);
map.put(score, player);
return;
}
}
}
}
}
答案 0 :(得分:2)
您可能需要查看PriorityQueue
,这样您就不需要迭代器...但如果元素超出限制,您应该从结尾删除元素
或者您应该使用SortedMap
:
public class T1 {
SortedMap<Integer, String> m=new TreeMap<Integer, String>();
void add(Integer i,String n){
m.put(i,n);
if(m.size()>3){
m.tailMap(m.lastKey()).clear();
}
System.out.println(m);
}
public static void main(String[] args) {
T1 t = new T1();
t.add(1,"a");t.add(2,"b");t.add(3,"c");t.add(4,"d");t.add(0,"e");
}
}
答案 1 :(得分:1)
您可以只查看底层TreeMap的lastKey,而不是迭代器。如果新条目更大,请接受它。
类似的东西:
int lastKey = map.getLastKey();
if (lastKey < score) {
map.remove(lastKey);
map.put(score, player);
}
答案 2 :(得分:1)
根据SO的输入,这就是我所做的(现在不用担心同步)
class ScoreMap {
SortedMap<Integer, String> map = new TreeMap<Integer, String>(Collections.reverseOrder());
int max = 5;
public ScoreMap(int maxCapacity) {
this.max = maxCapacity;
}
public void put(int score, String player) {
map.put(score, player);
if (map.size() > max) {
map.remove(map.lastKey());
}
}
//....
}