Solution for Intersection of Two Arrays II (C++)


  • 0
    B

    class Solution {
    public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
    unordered_map<int, int> first;
    vector<int> newA;

        for(auto n : nums1){
            if(first.find(n) == first.end()){
                first.emplace(n, 1);    
            }else{
                first[n]++;
            }
        }
        for(auto second : nums2){
            if(first.find(second) == first.end()){
                continue;
            }else if(first[second] == 0){
                continue;
            }else{
                first[second] -= 1;
                newA.push_back(second);
            }
        }
        return newA;
    }
    

    };


Log in to reply
 

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