two the intersection of the array
two the intersection of the array
Example: Nums1 = [1, 2, 2, 1] , Nums2 = [2, 2] , return [2] .
Solution one: With two hashset
Public int[] Intersection (int[] nums1,int[] nums2) {Set<Integer> set =NewHashset<integer>(); Set<Integer> inter =NewHashset<>(); for(inti=0; i<nums1.length; i++) {Set.add (nums1[i]); } for(intj=0; j<nums2.length; J + +){ if(Set.contains (Nums2[j])) {Inter.add (nums2[j]); } } int[] rst =New int[Inter.size ()]; intK = 0; for(Integer s:inter) {rst[k++] =s; } returnrst;}
Answer two: Sort two arrays, and then iterate through them with one pointer.
Public int[] Intersection (int[] nums1,int[] nums2) {Set<Integer> set =NewHashset<integer>(); Arrays.sort (NUMS1); Arrays.sort (NUMS2); intI=0, j=0; while(I<nums1.length && j<nums2.length) { if(nums1[i]<Nums2[j]) {i++; }Else if(nums1[i]>Nums2[j]) {J++; }Else{set.add (nums1[i]); I++; J++; } } int[] arr =New int[Set.size ()]; intK = 0; for(Integer s:set) {arr[k++] =s; } returnarr;}
Solution Three: Sort the num2, then traverse the number in the NUM1, make a binary search in num2, find it and put it in the set.
Lintcode Array (ii)