题目:
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.
翻译:
给定两个数组,写一个函数计算他们的交集。
例子:
给定 nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回[2]
.
扫描二维码关注公众号,回复:
940746 查看本文章
注意:
- 结果中的每个元素都是独一无二的。
- 结果可以是任何顺序的。
思路:
因为交集中的数字不得重复,因此,先用一个集合 s 存储 nums1 中所有不重复的数字,然后利用这个集合 s 中的数字和 nums2 中的元素进行对比,若 nums2 中的元素在集合 s 中,那么说明该元素是 nums2 和 nums1 的交集,用另外一个集合 t 来存储交集的结果。
C++代码(Visual Studio 2017):
#include "stdafx.h" #include <iostream> #include <vector> #include <set> using namespace std; class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> s(nums1.begin(), nums1.end()); set<int> t; for (int i = 0; i < nums2.size(); i++) { if (s.count(nums2[i])) { t.insert(nums2[i]); } } vector<int> result(t.begin(), t.end()); return result; } }; int main() { Solution s; vector<int> nums1 = { 1,2,2,1 }; vector<int> nums2 = { 2,2 }; vector<int> result; result = s.intersection(nums1, nums2); for (int i = 0; i < result.size(); i++) { cout << result[i] << " "; } return 0; }