2016-04-17 73 views
-2

我有以下问题。 我需要实现一个方法来比较两个数组,并找到给定数组的元素不匹配的第一个索引。 我曾尝试下面的代码,但它有点弱:比较两个阵列,并找到阵列不匹配的索引在JAVA

public int UnmatchedElementsOnIndex(int[] x, int[] y) { 

    for (int i = 0; i < x.length; i++) { 
     for (int j = 0; j < y.length; j++) { 
      if (x[i] == y[j]) { 
       // value is contained in both arrays 
      } 
      // otherwise not 
     } 
     return 0; 
    } 
+1

这是错误的。你可以做一个单一的循环和一些if语句。 –

+0

如果发现一个不匹配的元素,我使用额外的变量来计算++,但我不知道如何实现这个 –

+0

自己试试看,而不是从SO分数查找者那里寻找答案:P。你能行的。 –

回答

0

试试这个:

public int UnmatchedElementsOnIndex(int[] x, int[] y) { 

     // Also check for the list length 
     if(x.length < y.length) 
      return x.length; 
     else if(y.length < x.length) 
      return y.length; 

     for (int i = 0; i < x.length; i++) { 
       if(x[i] != y[i]) return i; 
      } 
      return -1; 
     } 

它将返回-1,如果在两个数组的所有元素都是相同的,othewise返回时,第一个索引数组在同一位置不包含相同的元素。

+0

循环时可能导致ArrayIndexOutOfBoundException。 –

0

你只需要扫描数组中的每个元素。然后确定哪个元素不匹配。以下是实现这一点的一种方法。

public int UnmatchedElementsOnIndex(int[] x, int[] y) { 
    int index=-1; 
    //lengths should be equal. If not, we can't compare arrays 
    if(x.length!=y.length){ 
     return -2; 
    } 
    for (int i = 0; i < x.length; i++) { 
     if (x[i] != y[i]) { 
      index=i; 
      break; 
     } 
    } 
    //returns -1, if all the elements are equal 
    return index; 
} 
+0

这有帮助!谢谢 –

-1
public int UnmatchedElementsOnIndex(int[] x, int[] y) { 
    for (int i = 0; i < x.length && i < y.length; i++) { 
     if (x[i] != y[i]) { 
      return i; 
     } 
     return -1; 
    } 
} 
0

第一关:有这样做的几种方法。

假设你要比较两个int []可以缩短你这样的代码:

public static int getDifferIndex(int[] a, int[] b) { 
     int i = 0; 
     while (i < a.length && i < b.length && a[i] == b[i++]); 
     return i; 
    } 

这里试试:https://ideone.com/zl0Hji

假设你想以该实现的对象的作品更广泛的解决方案boolean equals(Object)你可以把它改写成这样的:

public static int getDifferIndex(Object[] a, Object[] b) { 
     int i = 0; 
     while (i < a.length && i < b.length && a[i].equals(b[i++])); 
     return i; 
    }