Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Description:
- The output frequency of each element appears, should be consistent with the number of elements that appear in both arrays.
- We can not consider the order of output.
Advanced:
- If given array is already sorted it? How will you optimize your algorithm?
- If nums1 size than nums2 much smaller, which method is better?
- If nums2 elements stored on disk, the disk memory is limited and you can not be loaded once all the elements into memory, how can you do?
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
int p=0;
int q=0;
vector<int> t;
for(;p<nums1.size()&&q<nums2.size();){
if(nums1[p]==nums2[q]){
t.push_back(nums1[p]);
p++;
q++;
}else if(nums1[p]>nums2[q]){
q++;
}else if(nums1[p]<nums2[q]){
p++;
}
}return t;
}
};