Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Time: O(M*logM + N*logN); Space: extra space needed for sorting
// 方法1classSolution{publicint[]intersection(int[]nums1,int[]nums2){HashSet<Integer> set1 =newHashSet<>();for(int n : nums1)set1.add(n);HashSet<Integer> resSet =newHashSet<>();for(int n : nums2){if(set1.contains(n))resSet.add(n);}int[] res =newint[resSet.size()];int index =0;for(int n : resSet) res[index++]= n;return res;}}// 方法2classSolution{publicint[]intersection(int[]nums1,int[]nums2){Arrays.sort(nums1);Arrays.sort(nums2);Set<Integer> set =newHashSet<>();int i =0, j =0;while(i <nums1.length&& j <nums2.length){if(nums1[i]< nums2[j]) i++;elseif(nums1[i]> nums2[j]) j++;else{set.add(nums1[i]); i++; j++;}}int[] res =newint[set.size()];int k =0;for(Integer n : set){ res[k++]= n;}return res;}}
350. Intersection of Two Arrays II
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
We modify Approach 1 to count only elements which belong to the given numeric sub-range.
We process each numeric sub-ranges one by one until we process all numeric sub-ranges.
For example:
Input constraint:
1 <= nums1.length, nums2.length <= 10^10.
0 <= nums1[i], nums2[i] < 10^5
Our memory can store up to 1000 elements.
Then we split the numeric range into numeric sub-ranges [0...999], [1000...1999], ..., [99000...99999], then call Approach 1 to process 100 numeric sub-ranges.