Algorithm to find if two sets intersect

后端 未结 7 1844
一向
一向 2021-01-01 23:22

Let\'s say I have two arrays:

int ArrayA[] = {5, 17, 150, 230, 285};

int ArrayB[] = {7, 11, 57, 110, 230, 250};

Both arrays a

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 00:10

    Pretend that you are doing a mergesort, but don't send the results anywhere. If you get to the end of either source, there is no intersection. Each time you compare the next element of each, if they are equal, there is an intersection.

    For example:

    counterA = 0;
    counterB = 0;
    for(;;) {
        if(counterA == ArrayA.length || counterB == ArrayB.length)
            return false;
        else if(ArrayA[counterA] == ArrayB[counterB])
            return true;
        else if(ArrayA[counterA] < ArrayB[counterB])
            counterA++;
        else if(ArrayA[counterA] > ArrayB[counterB])
            counterB++;
        else
            halt_and_catch_fire();
    }
    

提交回复
热议问题