Intersection of Two Arrays II
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 tonums2'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?
可以考虑集合里交集的算法,由于两个集合内的每个元素都不需唯一且无序,我们可以考虑在有序状况下,如果某个值在第一个set中出现m次,在第二个set中出现n次,那么该值在输出区间中会出现min(m,n)次,存到一个新的vector中即可。
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2)
{
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
vector<int>::iterator first=nums1.begin();
vector<int>::iterator second=nums2.begin();
vector<int> res;
while(first!=nums1.end()&second!=nums2.end())
{
if(*first==*second)
{
res.push_back(*first);
first++;
second++;
}
else if(*first>*second)
{
second++;
}
else
{
first++;
}
}
return res;
}
};