The intersection of two sorted arrays

后端 未结 8 1426
臣服心动
臣服心动 2020-11-29 02:21

Given two sorted arrays: A and B. The size of array A is La and the size of array B is Lb. How

相关标签:
8条回答
  • 2020-11-29 02:54

    Let's consider two sorted arrays: -

    int[] array1 = {1,2,3,4,5,6,7,8};
    int[] array2 = {2,4,8};
    
    int i=0, j=0;    //taken two pointers
    

    While loop will run till both pointers reach up to the respective lengths.

    while(i<array1.length || j<array2.length){
        if(array1[i] > array2[j])     //if first array element is bigger then increment 2nd pointer
           j++;
        else if(array1[i] < array2[j]) // same checking for second array element
          i++;
        else {                         //if both are equal then print them and increment both pointers
            System.out.print(a1[i]+ " ");
    
            if(i==a1.length-1 ||j==a2.length-1)   //one additional check for ArrayOutOfBoundsException
                break;
            else{
                i++;
                j++;
            }
        }
    }        
    

    Output will be: -

    2 4 8
    
    0 讨论(0)
  • 2020-11-29 02:55

    Use set_intersection as here. The usual implementation would work similar to the merge part of merge-sort algorithm.

    0 讨论(0)
  • 2020-11-29 02:59

    Very Simple with the PYTHON

    Example: A=[1,2,3,5,7,9,90] B=[2,4,10,90]

    Here we go three lines of code

    for i in A:
         if(i in B):
            print(i)
    

    Output:2, 90

    0 讨论(0)
  • 2020-11-29 03:01

    Since this looks like a HW...I'll give you the algorithm:

    Let arr1,arr2 be the two sorted arrays of length La and Lb.
    Let i be index into the array arr1.
    Let j be index into the array arr2.
    Initialize i and j to 0.
    
    while(i < La and j < Lb) do
    
        if(arr1[i] == arr2[j]) { // found a common element.
            print arr[i] // print it.
            increment i // move on.
            increment j
        }
        else if(arr1[i] > arr2[j])
            increment j // don't change i, move j.
        else
            increment i // don't change j, move i.
    end while
    
    0 讨论(0)
  • 2020-11-29 03:02

    I've been struggling with same problem for a while now, so far I came with:

    1. Linear matching which will yield O(m+n) in worst case. You basically keep two pointers (A and B) each pointing to beginning of each array. Then advance pointer which points to smaller value, until you reach end of one of arrays, that would indicate no intersection. If at any point you have *A == *B - here comes your intersection.

    2. Binary matching. Which yields ~ O(n*log(m)) in worst case. You basically pick smaller array and perform binary search in bigger array of all elements of the smaller array. If you want to be more fancy, you can even use last position where binary search failed and use it as starting point for next binary search. This way you marginally improve worst case but for some sets it might perform miracles :)

    3. Double binary matching. It's a variation of regular binary matching. Basically you get element from the middle of smaller array and do binary search in bigger array. If you find nothing then you cut smaller array in half (and yes you can toss element you already used) and cut bigger array in half (use binary search failure point). And then repeat for each pair. Results are better than O(n*log(m)) but I am too lazy to calculate what they are.

    Those are two most basic ones. Both have merits. Linear is a bit easier to implement. Binary one is arguably faster (although there are plenty of cases when linear matching will outperform binary).

    If anyone knows anything better than that I would love to hear it. Matching arrays is what I do these days.

    P.S. don't quote me on terms "linear matching" and "binary matching" as I made them up myself and there are probably fancy name for it already.

    0 讨论(0)
  • 2020-11-29 03:04

    This is in Java, but it does what you want. It implements variant 3 mentioned in Nazar's answer (a "double" binary search) and should be the fastest solution. I'm pretty sure this beats any kind of "galloping" approach. Galloping just wastes time getting started with small steps while we jump right in with a top-down binary search.

    It's not immediately obvious which complexity class applies here. We do binary searches in the longer array, but never look at the same element twice, so we are definitely within O(m+n).

    This code has been thoroughly tested with random data.

    import java.util.Arrays;
    
    // main function. may return null when result is empty
    static int[] intersectSortedIntArrays(int[] a, int[] b) {
      return intersectSortedIntArrays(a, b, null);
    }
    
    // no (intermediate) waste version: reuse buffer
    static int[] intersectSortedIntArrays(int[] a, int[] b, IntBuffer buf) {
      int i = 0, j = 0, la = lIntArray(a), lb = lIntArray(b);
      
      // swap if a is longer than b
      if (la > lb) {
        int[] temp = a; a = b; b = temp;
        int temp2 = la; la = lb; lb = temp2;
      }
      
      // special case zero elements
      if (la == 0) return null;
      
      // special case one element
      if (la == 1)
        return Arrays.binarySearch(b, a[0]) >= 0 ? a : null;
        
      if (buf == null) buf = new IntBuffer(); else buf.reset();
      intersectSortedIntArrays_recurse(a, b, buf, 0, la, 0, lb);
      return buf.toArray();
    }
    
    static void intersectSortedIntArrays_recurse(int[] a, int[] b, IntBuffer buf, int aFrom, int aTo, int bFrom, int bTo) {
      if (aFrom >= aTo || bFrom >= bTo) return; // nothing to do
      
      // start in the middle of a, search this element in b
      int i = (aFrom+aTo)/2;
      int x = a[i];
      int j = Arrays.binarySearch(b, bFrom, bTo, x);
    
      if (j >= 0) {
        // element found
        intersectSortedIntArrays_recurse(a, b, buf, aFrom, i, bFrom, j);
        buf.add(x);
        intersectSortedIntArrays_recurse(a, b, buf, i+1, aTo, j+1, bTo);
      } else {
        j = -j-1;
        intersectSortedIntArrays_recurse(a, b, buf, aFrom, i, bFrom, j);
        intersectSortedIntArrays_recurse(a, b, buf, i+1, aTo, j, bTo);
      }
    }
    
    
    static int lIntArray(int[] a) {
      return a == null ? 0 : a.length;
    }
    
    
    static class IntBuffer {
      int[] data;
      int size;
      
      IntBuffer() {}
      IntBuffer(int size) { if (size != 0) data = new int[size]; }
      
      void add(int i) {
        if (size >= lIntArray(data))
          data = resizeIntArray(data, Math.max(1, lIntArray(data)*2));
        data[size++] = i;
      }
      
      int[] toArray() {
        return size == 0 ? null : resizeIntArray(data, size);
      }
      
      void reset() { size = 0; }
    }
    
    static int[] resizeIntArray(int[] a, int n) {
      if (n == lIntArray(a)) return a;
      int[] b = new int[n];
      arraycopy(a, 0, b, 0, Math.min(lIntArray(a), n));
      return b;
    }
    
    static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
      if (n != 0)
        System.arraycopy(src, srcPos, dest, destPos, n);
    }
    
    0 讨论(0)
提交回复
热议问题