public int[] intersection(int[] nums1,int[] nums2){
  if (nums1.length > nums2.length)   intersection(nums2,nums1);
  Set<Integer> set=new HashSet<>(nums1.length);
  for (  int n : nums1) {
    set.add(n);
  }
  Set<Integer> intersect=new HashSet<>(nums1.length);
  for (  int n : nums2) {
    if (set.contains(n)) {
      intersect.add(n);
    }
  }
  int[] result=new int[intersect.size()];
  int i=0;
  for (  Integer num : intersect) {
    result[i++]=num;
  }
  return result;
}

public int [ ] intersection ( int [ ] nums1 , int [ ] nums2 ) { if ( nums1 . length > nums2 . length ) intersection ( nums2 , nums1 ) ; Set < Integer > set = new HashSet < > ( nums1 . length ) ; for ( int n : nums1 ) { set . add ( n ) ; } Set < Integer > intersect = new HashSet < > ( nums1 . length ) ; for ( int n : nums2 ) { if ( set . contains ( n ) ) { intersect . add ( n ) ; } } int [ ] result = new int [ intersect . size ( ) ] ; int i = 0 ; for ( Integer num : intersect ) { result [ i ++ ] = num ; } return result ; }
two hash sets . one hash set for one array . the other for the intersection .
