Java Array Intersect intersectArrays(int[] a, int[] b)

Here you can find the source of intersectArrays(int[] a, int[] b)

Description

Returns the size of the intersection of two SORTED arrays.

License

Creative Commons License

Parameter

Parameter Description
a First array
b Second array

Return

Size of intersection of a and b

Declaration

public static int intersectArrays(int[] a, int[] b) 

Method Source Code

//package com.java2s;
/** //from w  ww . j  av  a 2s . c o m
This class is part of the Java Tools (see http://mpii.de/yago-naga/javatools).
It is licensed under the Creative Commons Attribution License 
(see http://creativecommons.org/licenses/by/3.0) by 
the YAGO-NAGA team (see http://mpii.de/yago-naga)
    
Some utility methods for arrays
*/

public class Main {
    /**
     * Returns the size of the intersection of two SORTED arrays.
     * The arrays NEED TO BE PASSED SORTED.
     * 
     * @param a First array
     * @param b Second array
     * @return  Size of intersection of a and b
     */
    public static int intersectArrays(int[] a, int[] b) {
        int intersectCount = 0;

        int aIndex = 0;
        int bIndex = 0;

        while (aIndex < a.length && bIndex < b.length) {
            if (a[aIndex] == b[bIndex]) {
                intersectCount++;

                aIndex++;
                bIndex++;
            } else if (a[aIndex] < b[bIndex]) {
                aIndex++;
            } else {
                bIndex++;
            }
        }

        return intersectCount;
    }
}

Related

  1. intersect(int[]... arrays)
  2. intersect(String[] arr1, String[] arr2)
  3. intersect(String[] list1, String[] list2)
  4. intersect(T[] a, T[] b)
  5. intersect(T[] a, T[] b)
  6. intersectArrays(int[] targetArray, int[] selfArray)
  7. intersection(final long[] array1, final long[] array2)
  8. intersection(int[] array1, int[] array2)
  9. intersection(String[] ary1, String[] ary2)