2014-02-10 90 views
-3

如何通过二进制搜索索引位置

int curIndex = Collections.binarysearch(myList,"String"); 
int highIndex = ? 
+0

你这是什么意思lowIndex?它返回列表中项目的索引(如果它存在)。 – Reddy

+0

你是否在第一次和最后一次出现“String”的索引之后(假设有多个出现),或者你是否像'highIndex = lowIndex +“String”.length()'之类的东西? – Edd

回答

4

你已经做出不正确的假设键值获得Collections.binarysearch()最高和最低指数的位置是:返回的值将以最低的指数。从documentation

如果列表包含多个元素等于指定的对象,则不能保证会找到哪个元素。

基本上,一旦你发现一个比赛,你只需要走的列表,直到找到不匹配,以获得最低的指数,然后步行列表,直到找到一个非匹配得到最高的索引。

int found = Collections.binarySearch(myList, "String"); 
int lowIndex = found; 
while (lowIndex > 0 && myList.get(lowIndex - 1).equals("String")) { 
    lowIndex--; 
} 
int highIndex = found; 
while (highIndex + 1 < myList.size() 
     && myList.get(highIndex + 1).equals("String")) { 
    highIndex++; 
} 

(你可以重写这些while循环为for循环用空的身体,如果你想,但我觉得这更易读。)