簡體   English   中英

創建一個函數來檢查數組中的任何索引是否具有相同的值

[英]Create a function that checks to see if any indexes in the array are of the same value

我正在嘗試創建一個函數來檢查數組中是否有兩個索引具有相同的值。 我已經意識到下面的代碼僅檢查第一個索引是否與第二個索引相同,而不檢查第一個索引是否與第三個,第四個索引相同,依此類推。

我嘗試在for循環中使用for循環比較每個索引,但是我不知道如何使它工作。

由於我當前的實現,由於i + 1超出了數組的長度,因此我也獲得了索引超出范圍的異常。

如果有人可以幫助解決代碼並向我解釋它如何工作,那就太好了! 謝謝!

public class Values {


public static void main (String[]args){

    int[] A = {0,1,2,1,4};

    for(int i = 0;i<=A.length;i++){

        int n = i+1;
        if(A[i] == A[n]){

        System.out.println("Index " + i + " is the same value as index " + n);
        System.out.println("Therefore, not all of the values in the array are different");
            break;
        }

    }
    System.out.println("All indexes in the array contain different values");
}

}
for(int i = 0; i < A.length - 1; i++){
    for(int j = i + 1; j < A.length; j++){
        if(A[i] == A[j]){
           //do something
        }
    }
}

最有效的方法是先排序,然后查找兩個相鄰元素是否相等:

Arrays.sort(A);
for (int i = 0; i < A.length - 1; i++) 
    if (A[i] == A[i+1])
        // do something

由於排序,該算法的時間復雜度為O(n log n)。

使用嵌套循環的時間復雜度為O(n 2 ),即使數組大小適中,也會開始受到損害。 再加上代碼更簡單。

出現邊界異常的原因是因為數組的長度為5(1、2、3、4、5個元素),但是只能訪問索引A [0],...,A [4]-因此,您應該像這樣遍歷數組: for(int i = 0;i<A.length;i++)

public class Values {


    public static void main (String[]args){

        int[] a = {0,1,2,1,4};
        boolean foundMatch = false;

        for(int i = 0;i < a.length; i++){

            if (foundMatch)
                break;

            for (int j = i+1; j < a.length; j++) {


                if (a[i] == a[j]){
                    System.out.println("Index " + i + " & " + j + " contain the same element: " + a[i] + "\nEnding comparison.");
                    foundMatch = true;
                    break;


                    }

            }


        }
        if(!foundMatch)
            System.out.println("All indexes in the array contain different values");
    }

}

暫無
暫無

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

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