350. Intersection of Two Arrays II
https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
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?
Thoughts
找两个数组的交集,允许重复元素。用freq map,nums1 -1,nums2 +1,当结果小于等于0时是交集元素。
可以用map记录频率. 这里假设排好序了, 和I的解法一样.
如果一个特别小另一个特别大, 可以把小的放进hash map, 然后每次从大的读入小的那么多. 或者对大的排序(external sort), 然后两指针或者二分法.
https://discuss.leetcode.com/topic/45992/solution-to-3rd-follow-up-question/3?page=1
参考follow up的答案.
Code
Analysis
取决于是否排好序.
Last updated
Was this helpful?