首页 > 解决方案 > 如何使用 Binary Search 打印两个不同 ArrayLists 中匹配索引的所有字符串?

问题描述

我使用以下方法找到了来自两个不同列表的两个字符串之间的匹配索引:

index = Collections.binarySearch(aList, bList);

但是,有多个字符串与 aList 中的一个匹配。我可以使用以下方法减少索引以找到 bList 中的第一个索引匹配:

if (index >= 0 ){

        while (aList.get(index-1) != bList){

            --index;

            break;

        }

但是我只能找到第一场比赛。我尝试过的所有代码都不适用于从第一个匹配到最后一个匹配递增并从每个匹配索引输出所有字符串。有没有办法解决这个问题?我将衷心感谢您的帮助!

标签: javaarraylistbinary-search

解决方案


这是更正和完成的版本:

    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().


推荐阅读