【问题标题】:Create a function that checks to see if any indexes in the array are of the same value创建一个函数来检查数组中的任何索引是否具有相同的值
【发布时间】:2015-09-17 22:48:52
【问题描述】:

我正在尝试创建一个函数来检查数组中的任何两个索引是否具有相同的值。我意识到我下面的代码只检查第一个索引是否与第二个索引相同,而不检查第一个索引是否与第三个、第四个等相同。

我尝试在 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");
}

}

【问题讨论】:

  • 数组元素,你的意思是,不是索引?索引必须是唯一的。
  • 提示:需要比较 A[i] 和 A[i + 1],还需要比较 A[i + 2], A[i + 3]... A[length - 1] .

标签: java arrays indexing


【解决方案1】:
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
        }
    }
}

【讨论】:

    【解决方案2】:

    最有效的方法是先排序,然后查找任意两个相邻元素是否相等:

    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(n2) 时间复杂度,即使是适度的数组大小也会开始受到影响。加上代码更简单。

    【讨论】:

    • 我提出了 n(n+1)/2 次迭代的算法。它不包含交换操作,而只包含比较。您如何看待,n 应该多大才能使您的算法显示更好的基准?
    • @sloth 我跑了一些公平的基准测试:如果值的范围很窄(例如与数组长度相同),所以重复的频率很高,嵌套循环的性能通常比 sort+loop 高 10-100次(数组越大,嵌套执行与排序+循环相比越好)。但是,如果被欺骗的情况不常见,那么排序+循环会在大型数组中获胜。当值的范围约为 500 * 数组长度时发生交叉,但在较小的数组大小(
    【解决方案3】:

    出现越界异常的原因是数组的长度为 5(1,2,3,4,5 个元素),但只有索引 A[0],...,A[4] 可以被访问 - 因此你应该像这样通过一个数组循环:for(int i = 0;i&lt;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");
        }
    
    }
    

    【讨论】:

    • 两个循环都不需要从 0 到 length,看看 Sloth 的回答。那么你不必检查 i == j。
    猜你喜欢
    • 1970-01-01
    • 2014-02-03
    • 2020-05-27
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多