My question is very basic, but I couldn't find the solution myself.
我的問題非常基礎,但我自己找不到解決方案。
I am used to writing algorithms in C++. There I very often use the std::map structure, together with all the auxiliary methods it provides.
我習慣用C ++編寫算法。我經常使用std :: map結構及其提供的所有輔助方法。
This method returns iterator to the first element of the map with key >= to the key given as parameter. Example:
此方法將迭代器返回到地圖的第一個元素,其中鍵> =到作為參數給出的鍵。例:
map m;
// m = { 4 => "foo", 6 => "bar", 10 => "abracadabra" }
m.lower_bound(2); // returns iterator pointing to <4, "foo">
m.lower_bound(4); // returns iterator pointing to <4, "foo">
m.lower_bound(5); // returns iterator pointing to <6, "bar">
The cool thing is that the C++ map is based on red-black trees and so the query is logarithmic (O(log n)).
很酷的是C ++映射基於紅黑樹,因此查詢是對數的(O(log n))。
Now I need to implement a certain algorithm in Java. I need similar functionality as the one I just described. I know I can use TreeMap which is implemented in ordered tree. However I don't seem to find equivalent of the method lower_bound. Is there such?
現在我需要在Java中實現某種算法。我需要與我剛才描述的功能類似的功能。我知道我可以使用在有序樹中實現的TreeMap。但是我似乎沒有找到相同的方法lower_bound。有這樣的嗎?
Thank you very much for your help.
非常感謝您的幫助。
4 个解决方案
#1
6
I guess that you're looking for TreeMap. Take a look at ceilingKey/Entry methods.
我猜你正在尋找TreeMap。看看ceilingKey / Entry方法。
#2
1
I hope this works for you?
我希望這對你有用嗎?
SortedMap tail = .tailMap(target);
if (!tail.isEmpty())
{
upper = tail.firstKey();
}
#3
1
This is a test case that shows behaviour:
這是一個顯示行為的測試用例:
@Test
public void testPrefixMatch() {
treeMap.put("1.2.3", "bar");
treeMap.put("1.2.3.4", "bar");
treeMap.put("1.2.3.5.6", "bar");
assertEquals("1.2.3.5.6", treeMap.ceilingKey("1.2.3.4.5.6.7"));
assertEquals("1.2.3.4", treeMap.floorKey("1.2.3.4.8.6"));
assertEquals("1.2.3.5.6", treeMap.ceilingKey("1.2.3.4.8.6"));
}
#4
0
kind of similar:
有點類似:
In C++
vector lower_bound return the index
In Java
TreeSet higher return the Key