【问题标题】:How do I print all strings from matching indexes in two different ArrayLists using Binary Search?如何使用二进制搜索从两个不同的 ArrayLists 中的匹配索引中打印所有字符串?
【发布时间】:2021-03-16 17:57:04
【问题描述】:

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

index = Collections.binarySearch(aList, bList);

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

if (index >= 0 ){

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

            --index;

            break;

        }

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

【问题讨论】:

标签: java arraylist binary-search


【解决方案1】:

这是更正和完成的版本:

    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() 返回的索引右侧找到匹配项。

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2017-11-04
    • 2021-05-29
    • 2020-09-27
    • 2016-09-25
    相关资源
    最近更新 更多