Fastest (runtime) way to check if two very long arrays have at least one common element?

Riccardo Barbieri :

I'm trying to check if two arrays have at least one common element, I've already tried a solution but it is not fast enough, it essentially consists of two nested loops, here is the code:

boolean oneElementChecker(int[] pArray1, int[] pArray2)
    while (i < pArray1.length) {

      j = 0;

      if (sameValueChecker)
        break;

      while (j < pArray2.length) {

        if ((pArray1[i] == pArray2[j]))
          sameValueChecker = true;

        j++;
      }

      i++;
    }

    return !sameValueChecker;

I'd need to know if there are ways to make this task faster.

Ankur :

If space is not an issue, then what I probably would suggest is the use of HASHING.

First, create a hashset of elements of array pArray1. ( This would be done in O(n) time complexity).

Then, start traversing the second array, and for each element look it up in the hashset for existence (Note : hashset lookup is O(1) operation). Continue traversal until either you find an element in hashset or second array pArray2 reaches its end.

So, essentially using hashing, you would eliminate the nested loops and you final time complexity would come out to be O(n) (O(n) + O(n) ).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141879&siteId=1