Algorithm to find added/removed elements in an array

Posted by jj on Stack Overflow See other posts from Stack Overflow or by jj
Published on 2010-05-04T11:11:38Z Indexed on 2010/05/04 11:28 UTC
Read the original article Hit count: 215

Filed under:
|
|
|

Hi all,

I am looking for the most efficent way of solving the following

Problem:

given an array Before = { 8, 7, 2, 1} and an array After ={1, 3, 8, 8}
find the added and the removed elements

the solution is:
        added = 3, 8 
        removed = 7, 2, 1

My idea so far is:

for i = 0 .. B.Lenghtt-1
{
    for j= 0 .. A.Lenght-1
    {
        if A[j] == B[i]

            A[j] = 0;
            B[i] = 0;

            break;
    }
}

// B elemnts different from 0 are the Removed elements
// A elemnts different from 0 are the Added elemnts

Does anyone know a better solution perhaps more efficent and that doesn't overwrite the original arrays

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about array