leetcode 350: Intersection of Two Arrays II

Title: Intersection of Two Arrays II

  • Topic description:
    Given two arrays, write a method to compute their intersection.
    For example:
    given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
    Note:
  • The number of occurrences of each element in the output should be the same as the number of occurrences of the element in the two arrays.
  • We can ignore the order of output results.

Follow up:
what if the given array is already sorted? How would you optimize your algorithm?
If the size of nums1 is much smaller than nums2, which method is better?
If the elements of nums2 are stored on disk and memory is limited, you can't load all the elements into memory at once, what should you do?

C++:
class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res;
        int i = 0,j = 0;
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        while(i<nums1.size()&&j<nums2.size()){
            if(nums1[i]==nums2[j]){
                res.push_back(nums1[i]);
                ++i;++j;
             }else if(nums1[i]>nums2[j]){
                 ++j;
             }else{
                 ++i;
             }
        }
        return res;
        }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325983483&siteId=291194637