简体   繁体   中英

Finding common elements in two arrays of different size

I have to find the best way to get common elements of two arrays of different size.

The arrays are unordered; the common elements are in different position, but in the same order (if in the array A common element b came after a , the same happens in array B) and with max distance N.

I can't use more additional space of O(N).

Actually I extract N elements from array A, order them with mergesort and perform a dicotomic search using N elements of array B. Then I get the next N elements from the position of the match I found and do another cycle.

The cost of this should be, using m as length of array B, O(m N log N)

I have tried using an hashtable, but to manage collisions I have to implement a List, and efficiency goes down.

There is a better way?

Assuming you can have "holes" in your matched sequence (A = [1,3,2] AND B = [1,4,2] Then MatchSet = {1,2})

Maybe I am wrong but you could try this pseudo code:

i <- 0; j <- 0; jHit <- -1
matchSet <- Empty
While i < Length(A) AND j < Length(B):
    If A[i] == B[j] Then
        matchSet.add(A[i])
        i <- i+1
        jHit <- j
    End If
    j <- j+1
    If j == Length(B) Then
        i <- i+1
        j <- jHit+1
    End If
End Loop

The first index (i) points to the next element of A not found in B whereas (j) is used to look for the next element of B (after the last element found in A).

This yould give you a time complexity of O(mN) and space usage of O(N).

Here you have an implementation in Python:

def match(A,B):
    i = 0
    j = 0
    jHit = -1
    res = []
    while i < len(A) and j < len(B):
        if A[i] == B[j]:
            res.append(A[i])
            i += 1
            jHit = j
        j += 1
        if j == len(B):
            i += 1
            j = jHit+1
    return res

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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