Share my C++ solution using set,easy to understand


  • 0
    V
    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            vector<int> ret;
            set<int> my_set1;
            set<int> my_set2;
            int i = 0;
            int len1 = nums1.size();
            int len2 = nums2.size();
            
            if (len1 == 0 || len2 == 0)
                return ret;
                
            for (i = 0; i < len1; i++)
                my_set1.insert(nums1[i]);
            for (i = 0; i < len2; i++)
                my_set2.insert(nums2[i]);
                
            set<int>::iterator s1 = my_set1.begin();
            set<int>::iterator s2 = my_set2.begin();
            
            while (s1 != my_set1.end() && s2 != my_set2.end())
            {
                if (*s1 == *s2)
                {
                    ret.push_back(*s1);
                    s1++;
                    s2++;
                }
                else if (*s1 < *s2)
                    s1++;
                else 
                    s2++;
            }
            
            return ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.