leetcode-349-intersection of two arrays

Problem Description:

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.

题目大意:

找到两个集合的交集,并且注意交集中每个元素只能出现一次。

Solutions:

很简单的hash map的题,遍历a中每一个元素,只要在b中出现的,如果没有添加过,则添加到结果集合中。

Code in C++:

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res;
        if(!nums1.empty()||!nums2.empty())
            for(int i=0;i<nums1.size();i++)
                {
                    if(find(nums2.begin(),nums2.end(),nums1[i])!=nums2.end())//if nums1[i] is in nums2
                        if(find(res.begin(),res.end(),nums1[i])==res.end())// if nums[i] not in res
                            res.push_back(nums1[i]);
                }
            return res;

    }
};