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 intersection(vector & nums1, vector & nums2) { vectorresult; set set1; set set2; set ::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