My C++ Solutions using set and unordered_set


  • 3
    H

    Using set 20ms

    class Solution {
    public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> st1(nums1.begin(),nums1.end());
        set<int> st2(nums2.begin(),nums2.end());
        set<int> intersection; 
        set_intersection(st1.begin(),st1.end(), st2.begin(), st2.end(), inserter(intersection, intersection.end())); 
        return vector<int>(intersection.begin(),intersection.end());
    }
    };
    

    Using unordered_set 12ms

    class Solution {
    public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> st1(nums1.begin(),nums1.end());
        unordered_set<int> st2(nums2.begin(),nums2.end());
        vector<int> ret;
        for(const auto & x:st1)
            if(st2.count(x))
                ret.push_back(x);
        return ret;
    }
    };
    

    Using unordered_set 12ms

    class Solution {
    public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> st(nums1.begin(),nums1.end());
        vector<int> ret;
        for(const auto & x:nums2)
            if(st.count(x))
            {
                ret.push_back(x);
                st.erase(x);
            }
        return ret;
    }
    };

Log in to reply
 

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