-1

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 }

SetY = { 0, 2, 4, 6 }

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

so 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.

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;
}
4

1 回答 1

1

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

  1. 如果 setX[a] > setY[b] -> b++
  2. 如果 setX[a] < setY[b] -> a++
  3. Else -> 将 setX[a] 添加到结果中,a++, b++
于 2016-12-06T16:32:17.643 回答