349. Intersection of Two Arrays

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

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

Note:
Each element in the result must be unique.
The result can be in any order.

Source Code(C++):

#include <iostream>
#include <vector>
#include <set>
using namespace std;

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> st;
        vector<int> res;
        for (vector<int>::iterator i=nums1.begin(); i!=nums1.end(); i++) {
            st.insert(*i);
        }
        for (vector<int>::iterator i=nums2.begin(); i!=nums2.end(); i++) {
            if (st.find(*i)!=st.end()) {
                res.push_back(*i);
                st.erase(*i);
            }
        }
        return res;
    }
};

int main() {
    Solution sol;
    vector<int> v1;
    vector<int> v2;
    vector<int> v3;
    v1.push_back(1);v1.push_back(2);v1.push_back(2);v1.push_back(1);
    v2.push_back(2);v2.push_back(2);
    v3=sol.intersection(v1, v2);
    for (vector<int>::iterator i=v3.begin(); i!=v3.end(); i++) {
        cout << *i << ' ';
    }
    cout << endl;
    v1.clear();
    v2.clear();
    v3=sol.intersection(v1, v2);
    for (vector<int>::iterator i=v3.begin(); i!=v3.end(); i++) {
        cout << *i << ' ';
    }

    return 0;
}

你可能感兴趣的:(349. Intersection of Two Arrays)