LeetCode 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.
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res;
        map<int, int> visited;
        for(int i=0; i<nums1.size(); i++)
            visited[nums1[i]]=1;
        for(int i=0; i<nums2.size(); i++)
            if(visited[nums2[i]]==1){
                res.push_back(nums2[i]);
                visited[nums2[i]]=2;
            }
        return res;
    }
};
posted @ 2018-12-03 21:43  A-Little-Nut  阅读(73)  评论(0编辑  收藏  举报