简体   繁体   English

尝试返回两个数组之间的差数

[英]Trying to return the number of differences between two arrays

So if I have two arrays 所以如果我有两个数组

int [] array1 = {1, 2, 3, 4}
int [] array2 = {1, 3, 2, 4}

This would return two as there are two differences in the arrays so far I have this but I can't figure it out. 这将返回两个,因为到目前为止数组中有两个差异,但是我无法弄清楚。

    public static int countDifferences(int[] array1, int[] array2){
    int differences = 0;
    for(int i=0; i<array1.length; i++) {
        for(int j=0; j<array2.length; j++) {
            if(array1[i]==array2[j]) {
                return 0;
            }
            else{
                differences++;
            }
        }
    }
    return differences;
}

You should just have a single for loop to iterate once over both arrays. 您应该只有一个for循环在两个数组上迭代一次。 You also need to handle the case where the two input arrays do not have the same length. 您还需要处理两个输入数组的长度不同的情况。 Also, one or both arrays could be empty. 同样,一个或两个阵列可能为空。 For these edge cases I am returning -1, though you can modify if you want. 对于这些极端情况,我将返回-1,不过您可以根据需要进行修改。

public static int countDifferences(int[] array1, int[] array2) {
    if (array1 == null || array2 == null || array1.length != array2.length) {
        return -1;
    }
    int differences = 0;

    for (int i=0; i < array1.length; i++) {
        if (array1[i] != array2[i]) {
            differences++;
        }
    }

    return differences;
}

This is a logic problem. 这是一个逻辑问题。

For your example, you are counting the same difference twice, since the switch of two location is really one switch. 在您的示例中,您两次计算相同的差值,因为两个位置的开关实际上是一个开关。 So check for that condition and count it as one. 因此,请检查该条件并将其计为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM