简体   繁体   中英

Constructing a O(n) time complexity algorithm for search for a value in two arrays

Say I have 2 int arrays that are sorted in ascending order. and I am trying to find if there is a value from Array A that matches a value in Array B while having a time complexity of Big-O of n. At first I thought of linear search but it wasnt possible because I needed a nested for loop. My other idea was trying to use a binary search and add an for loop to that. Would that work?

So like...

for (int i = 0;i<B.length(), i++) {
   BinarySearch(A[0..N-1], value, low, high) {
       if (high < low)
           return -1 // not found
       mid = low + (high - low) / 2
       if (A[mid] > value)
           return BinarySearch(A, value, low, mid-1)
       else if (A[mid] < value)
           return BinarySearch(A, value, mid+1, high)
       else
           return mid // found
   }
}

this isnt a complete code, I just copied this from wiki as an example. Am i going in the right direction?

You say the arrays are sorted already. That's the very important precondition you have to work with. Then, you have two sequences like this:

 1 <A   -7
 2       0
 5 <B    1 <A
10       5 <B
13      11
14      13

Imagine you walk the sequences in parallel from top to bottom, trying to balance indexes in such a way that values at those indexes match — see the marks <A and <B in my example. The rest is just using integer comparisons. That will result in an O(Max(a.Length, b.Length)) (hence O(n) ) time complexity.

Possible improvement: At the beginning figure out whether it makes sense to walk the inputs at all.

The rest if really left as a homework.

Merge both lists, merge is O(n).

Merge procedure would be:

1) Compare "smallest element" of both lists, if they are equal, it forms our answer. 2) If not remove the smaller of the two from the list and update the list. 3) Repeat 1) and 2) till any of the list is finished.

complexity would be Min(a.length, b.length) which may be O(1) also if one array is comparatively very small than other.

sample code to show how python is self explanatory ;)

def find_first_matching_value(array_a, array_b):
    "Return the first value in both arrays"
    # both arrays are sorted
    assert sorted(array_a) == array_a
    assert sorted(array_b) == array_b
    array_a_index = 0
    array_b_index = 0
    while (array_a_index < len(array_a)
           and array_b_index < len(array_b)):
        if array_a[array_a_index] > array_b[array_b_index]:
            # skip to next element in array b
            array_b_index += 1
        elif array_a[array_a_index] < array_b[array_b_index]:
            # skip to next element in array a
            array_a_index += 1
        else:
            # found
            return array_a[array_a_index]

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