java - 如何使用 Binary Search 打印两个不同 ArrayLists 中匹配索引的所有字符串?
问题描述
我使用以下方法找到了来自两个不同列表的两个字符串之间的匹配索引:
index = Collections.binarySearch(aList, bList);
但是,有多个字符串与 aList 中的一个匹配。我可以使用以下方法减少索引以找到 bList 中的第一个索引匹配:
if (index >= 0 ){
while (aList.get(index-1) != bList){
--index;
break;
}
但是我只能找到第一场比赛。我尝试过的所有代码都不适用于从第一个匹配到最后一个匹配递增并从每个匹配索引输出所有字符串。有没有办法解决这个问题?我将衷心感谢您的帮助!
解决方案
这是更正和完成的版本:
List<String> aList = List.of("Carrot", "Carrot", "Cauliflower",
"Mushroom", "Mushroom", "Mushroom", "Mushroom", "Pointed cabbage");
String bItem = "Mushroom";
int index = Collections.binarySearch(aList, bItem);
if (index >= 0) {
int firstIndexInclusive = index;
while (firstIndexInclusive > 0 && aList.get(firstIndexInclusive - 1).equals(bItem)) {
firstIndexInclusive--;
}
int lastIndexExclusive = index;
while (lastIndexExclusive < aList.size() && aList.get(lastIndexExclusive).equals(bItem)) {
lastIndexExclusive++;
}
// Print all matching entries
for (int i = firstIndexInclusive; i < lastIndexExclusive; i++) {
System.out.println("" + i + ": " + aList.get(i));
}
} else {
System.out.println("Not found");
}
输出是:
3: Mushroom 4: Mushroom 5: Mushroom 6: Mushroom
你的代码出了什么问题?
这条线有几个问题:
while (aList.get(index-1) != bList){
index
可能是 0(迟早),如果是,则aList.get(index-1)
抛出异常。与!=
通常比较不起作用,除非bList
是原始类型(而不是像对象这样的引用类型)(即使在这种情况下,它也不是推荐的可读方式)。
这行也是错误的:
break;
您在递减index
一次后退出循环,因此如果左侧有更多匹配项,则不包括它们。
最后,您显示的代码中没有任何内容可以在binarySearch()
.
推荐阅读
- git - Visual Studio 的 git 集成找不到我的文件的历史记录
- javascript - CSS:如何使 div 扩展到可滚动容器之外
- python - RuntimeError:堆栈期望每个张量与 fastaudio 模块大小相等
- java - 添加 MySQL/MariaDB 依赖会破坏 Maven/Jira-Plugin
- c# - 如何使活动指示器等待功能
- firebase - Nuxt SSR - Firebase 托管
- r - 需要帮助在 URL 列表上循环这些函数并将聚合数据组合到一个表中
- python - 将二维数组的二维数组转换为numpy中的二维数组
- django - 距离 Postgis Django Postgres
- sql - 在 SQL (Snowflake) 中将一行转换为布尔变量`