[Primary Algorithm] 6. Intersection II of Two Arrays

The topics are as follows:

Given two arrays, write a method to compute their intersection.

E.g:
Given nums1 = [ 1 , 2 , 2 , 1 ], nums2 = [ 2 , 2 ], return [ 2 , 2 ].

Notice:

   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?

Problem solving ideas:

1. You can use hash. Insert all the elements in array 1 into the hash list, and then search for each element in array 2. The time complexity is O(n) and the space complexity is O(N).

code show as below:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        map<int,int> cnt1;
        map<int,int> cnt2;
        vector<int> ret;
        
        for(int i = 0;i < nums1.size();++i){
            if(cnt1.find(nums1[i])!=cnt1.end()){  
                cnt1[nums1[i]]++;  
            }  
            else{  
                cnt1[nums1[i]] = 1;  
            }   
        }
        
        for(int i = 0;i < nums2.size();++i){
            if(cnt2.find(nums2[i])!=cnt2.end()){  
                cnt2[nums2[i]]++;  
            }  
            else{  
                cnt2[nums2[i]] = 1;  
            }  
        }
        
        map<int,int>::iterator it1;
        map<int,int>::iterator it1;
        for(it1 = cnt1.begin();it1!= cnt1.end();++it1){
            it2 = cnt1.find(it1->first);
            if(it2!=cnt2.end()){
                if(it2->second == it1->second){
                    for(int i = 0;i < it1->second; ++i){
                        ret.push_back(it1->first);
                    }
                }
            }
                
            
        }
        
        return ret;
    }
};

2. Sorted array. The sorted elements of the two arrays can be traversed in turn to find the same elements in the two arrays.

The C++ code is as follows:

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

 

Guess you like

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