[英]Sorted Iterable Efficient Sorted Structure in Java
我已經瀏覽了(可能是數十個)StackOverflow問題,但我認為我沒有找到想要的東西。
我想要具有以下屬性的Java結構:
為什么? 我正在實現一個k最近距離算法。 對於數據收集中的每個點,我需要找到到第k個最近的其他點的距離。 該算法的工作原理是遍歷每對點,計算它們之間的距離,然后將該距離添加到每個點的最近距離排序結構中(如果該距離比該列表中的其他元素更近)。 這是一些代碼來演示:
ArrayList<SortedThing<Double>> nearestDistances = new ArrayList<SortedThing<Double>>(numPoints);
for (int i = 0; i < numPoints; i++) {
nearestDistances.add(new SortedThing<Double>(k));
}
for (int point = 0; point < numPoints; point++) {
for (int otherPoint = point+1; otherPoint < numPoints; otherPoint++) {
double distance = computeDistance(point, otherPoint);
if (nearestDistances.get(point).size < k)
nearestDistances.get(point).add(distance);
else if (nearestDistances.get(point).last() > distance) {
nearestDistances.get(point).removeLast();
nearestDistances.get(point).add(distance);
}
if (nearestDistances.get(otherPoint).size < k)
nearestDistances.get(otherPoint).add(distance);
else if (nearestDistances.get(otherPoint).last() > distance) {
nearestDistances.get(otherPoint).removeLast();
nearestDistances.get(otherPoint).add(distance);
}
}
}
在您建議以下任何內置Java類之前,這就是我不想使用它們的原因:
有人知道這樣的結構嗎? 我最近一直在考慮這個問題,令我感到困惑的是Java沒有提供任何此類結構。
如果您正在進行最近鄰居搜索,則可能要使用kd樹 ; 這是一個Java實現 (在.jar文件的\\ bak目錄中查找源代碼)
否則,我建議使用TreeMap,其中的值是關鍵重復項的數量(1表示沒有重復項,2表示一個重復項,依此類推)
Map<Key, Integer> map = new TreeMap<>();
if(map.containsKey(key)) {
map.put(key, map.get(key) + 1);
} else {
map.put(key, 1);
}
從Apache Commons Collections中檢查TreeBag 。
TreeBag
使用TreeMap
來保存條目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.