簡體   English   中英

如何使用 Binary Search 打印兩個不同 ArrayLists 中匹配索引的所有字符串?

[英]How do I print all strings from matching indexes in two different ArrayLists using Binary Search?

我使用以下方法找到了來自兩個不同列表的兩個字符串之間的匹配索引:

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");
    }

Output 是:

 3: Mushroom 4: Mushroom 5: Mushroom 6: Mushroom

你的代碼出了什么問題?

這條線有幾個問題:

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

index可能是 0(遲早),如果是, aList.get(index-1)會拋出異常。 !=比較通常不起作用,除非bList是原始類型(不是像對象那樣的引用類型)(即使在這種情況下,它也不是推薦的可讀方式)。

這行也是錯誤的:

        break;

在減少一次index后,您將跳出循環,因此如果左側有更多匹配項,則不包括它們。

最后,您顯示的代碼中沒有任何內容可以在binarySearch()返回的索引右側找到匹配項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM