leetCode 349. Intersection of Two Arrays 哈希

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.

題目大意:

將兩個數組中一樣的元素存入結果數組返回。結果數組中的元素不能重複。

思路:

1.將數組1,數組2分別放入set中去重。

2.使用迭代器iterator遍歷set1,在set2中找與set1相同的元素,找到就添加到結果數組中。

代碼如下:

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int > result;
        set<int> set1;
        set<int> set2;
        set<int>::iterator it;
        
        for(int i = 0 ; i < nums1.size();i++)
            if(set1.find(nums1[i]) == set1.end())
                set1.insert(nums1[i]);
        for(int i = 0 ; i < nums2.size();i++)
            if(set2.find(nums2[i]) == set2.end())
                set2.insert(nums2[i]);
        for(it = set1.begin();it != set1.end();it++)
        {
            if(set2.find(*it) != set2.end() )
                result.push_back(*it);
        }
        
        return result;
    }
};

2016-08-13 16:22:39

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章