@@ -0,0 +1,1647 @@
+import java.util.Arrays;%0Aimport java.util.HashSet;%0Aimport java.util.Set;%0Aimport java.util.stream.Collectors;%0A%0A/**%0A * Given two arrays, write a function to compute their intersection.%0A * %3Cp%3E%0A * Example:%0A * Given nums1 = %5B1, 2, 2, 1%5D, nums2 = %5B2, 2%5D, return %5B2%5D.%0A * %3Cp%3E%0A * Note:%0A * Each element in the result must be unique.%0A * The result can be in any order.%0A * %3Cp%3E%0A * Tags: Binary Search, Hash Table, Two Pointers, Sort%0A * Similar Problems: (E) Intersection of Two Arrays II%0A */%0Apublic class IntersectionofTwoArrays %7B%0A%0A    /**%0A     * Two hash sets.%0A     * One hash set for one array. The other for the intersection.%0A     */%0A    public int%5B%5D intersection(int%5B%5D nums1, int%5B%5D nums2) %7B%0A        if (nums1.length %3E nums2.length)%0A            intersection(nums2, nums1);%0A        Set%3CInteger%3E set = new HashSet%3C%3E(nums1.length);%0A        for (int n : nums1) %7B%0A            set.add(n);%0A        %7D%0A        Set%3CInteger%3E intersect = new HashSet%3C%3E(nums1.length);%0A        for (int n : nums2) %7B%0A            if (set.contains(n)) %7B%0A                intersect.add(n);%0A            %7D%0A        %7D%0A        int%5B%5D result = new int%5Bintersect.size()%5D;%0A        int i = 0;%0A        for (Integer num : intersect) %7B%0A            result%5Bi++%5D = num;%0A        %7D%0A        return result;%0A    %7D%0A%0A    /**%0A     * Java 8 stream.%0A     * Convert one of the arrays to set using collect.%0A     * Then generate a distinct filtered stream from the other array.%0A     */%0A    public int%5B%5D intersectionJava8(int%5B%5D nums1, int%5B%5D nums2) %7B%0A        Set%3CInteger%3E set = Arrays.stream(nums2).boxed().collect(Collectors.toSet());%0A        return Arrays.stream(nums1).distinct().filter(set::contains).toArray();%0A    %7D%0A%7D%0A

add Intersection of Two Arrays