找到两个int数组之间的区别

时间:2021-11-30 19:16:35

I am having trouble figuring out the algorithm that will find the differences between two integer arrays. I already have a sorting method that it will be ran through so the numbers are in ascending order.

我无法找出能找到两个整数数组之间差异的算法。我已经有一个排序方法,它将被运行,所以数字是按升序排列的。

For example:

SetX = { 1, 2, 3, 4, 5 }

SetX = {1,2,3,4,5}

SetY = { 0, 2, 4, 6 }

SetY = {0,2,4,6}

The return should be the numbers in SetX that does not appear in SetY.

返回值应该是SetX中未出现在SetY中的数字。

so resultSet = { 1, 3, 5 }

所以resultSet = {1,3,5}

Sometimes I get the correct answer if I do small arrays but if I do arrays that are 4 or more Integers long it gives me the wrong return.

有时我会得到正确答案,如果我做小数组,但如果我做4个或更多整数的数组,它给我错误的回报。

Can someone look over my code and tell me what I am doing wrong?

有人可以查看我的代码并告诉我我做错了什么吗?

public static int firstFruit(int[] setX, int usedSizeSetX, int[] setY, int usedSizeSet2, int[] resultSet) {
    int a = 0, b = 0, c = 0;

    while( a < usedSizeSetX && b < usedSizeSetY){
        if(setX[a] == setY[b]) {
            a++;
        } else if(setX[a] == setY[b]){
            b++;
        } else {
            resultSet[c++] = setX[a++];
            b++;
        }
    }
    return c;
}

1 个解决方案

#1


1  

I think your conditionals are a little FUBAR. The processing should be:

我认为你的条件有点FUBAR。处理应该是:

  1. If setX[a] > setY[b] -> b++
  2. 如果setX [a]> setY [b] - > b ++

  3. If setX[a] < setY[b] -> a++
  4. 如果setX [a] a ++

  5. Else -> add setX[a] to the result, a++, b++
  6. 否则 - >将setX [a]添加到结果,a ++,b ++

#1


1  

I think your conditionals are a little FUBAR. The processing should be:

我认为你的条件有点FUBAR。处理应该是:

  1. If setX[a] > setY[b] -> b++
  2. 如果setX [a]> setY [b] - > b ++

  3. If setX[a] < setY[b] -> a++
  4. 如果setX [a] a ++

  5. Else -> add setX[a] to the result, a++, b++
  6. 否则 - >将setX [a]添加到结果,a ++,b ++