-3
A
回答
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
循環用空的身體,如果你想,但我覺得這更易讀。)
相關問題
- 1. 二進制搜索
- 2. 二進制搜索
- 3. 二進制搜索
- 4. 二進制搜索
- 5. 二進制搜索樹內的二進制搜索樹
- 6. 二進制搜索是/是二進制搜索貪婪算法?
- 7. 線性搜索或二進制搜索或二叉搜索樹
- 8. 二進制搜索樹,搜索方法
- 9. 二進制搜索樹搜索操作
- 10. 二進制搜索樹 - 搜索範圍
- 11. Swift二進制搜索樹搜索
- 12. C#在2個索引上進行二進制搜索
- 13. 二進制搜索範圍
- 14. Haskell - 二進制搜索樹
- 15. 二進制搜索樹Instantiaition
- 16. 二進制搜索功能
- 17. 二進制搜索程序
- 18. 二進制搜索樹C++
- 19. RandomAccessFile的二進制搜索
- 20. 遞歸二進制搜索
- 21. 與二進制搜索
- 22. 通用二進制搜索++
- 23. 二進制搜索問題?
- 24. 二進制遞歸搜索
- 25. 二進制搜索樹toString
- 26. 搜索二進制表
- 27. 二進制搜索CompareTo Java
- 28. C#二進制搜索
- 29. 二進制搜索用C
- 30. 使用二進制搜索
你這是什麼意思lowIndex?它返回列表中項目的索引(如果它存在)。 – Reddy
你是否在第一次和最後一次出現「String」的索引之後(假設有多個出現),或者你是否像'highIndex = lowIndex +「String」.length()'之類的東西? – Edd