且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

leetCode 349. Intersection of Two Arrays 哈希

更新时间:2022-10-03 13:53:08

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相同的元素,找到就添加到结果数组中。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
    }
};



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837597