Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example 1:
Example 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?
Analysis
这里讨论follow up的问题:
What if the given array is already sorted? How would you optimize your algorithm?
If both arrays are sorted, we could use two pointers to iterate, which is similar to the merge
two sorted array process.
Use two pointers. At start two pointers point to the first element of each array. If it is equal, push it to the answer then move both pointers to next position. Otherwise, move the one with less value to the next position.
Using two pointers will have O(M + N) time complexity
What if nums1 's size is small compared to nums2 's size? Which algorithm is better?
If using HashMap solution, the time complexity would be O(M + N), while space complexity is O(N), we can use nums1 to build the hash map, in order to reduce space complexity.
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?
If nums1 is small enough to store in memory, build a hashmap out of it, and read chunk by chunk from nums2, and check if it's in hashmap.
If both nums1 and nums2 are too large for in memory storage, do external sorting for both first, and read chunk by chunk for both sorted array, and then check intersection.
Solution
HashMap Approach - O(n) time, O(n) space
Sort two Arrays, then use two pointers
Last updated