Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
O(Min(N,M)) 時間 O(Min(N,M)) 空間app
先排序,用兩個指針從頭掃:
小的那個確定不行,指針日後
相等的全都放到result裏this
沒有指針
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); List<Integer> result = new ArrayList<Integer>(); int i = 0, j = 0; while (i < nums1.length && j < nums2.length) { int n1 = nums1[i]; int n2 = nums2[j]; if (n1 == n2) { result.add(n1); i++; j++; } else if (n1 < n2) i++; else j++; } int[] ret = new int[result.size()]; int k = 0; for (int num : result) ret[k++] = num; return ret; } }
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?code
If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections.排序
If both nums1 and nums2 are so huge that neither fit into the memory, sort them individually (external sort), then read (let's say) 2G of each into memory and then using the 2 pointer technique, then read 2G more from the array that has been exhausted. Repeat this until no more data to read from disk.element