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.
这个题比较简单,两个集合求交集,如果有多个元素只需要保存一个即可。可以使用set来存放结果,最后转换成vector即可。而且因为要求结果可以是无序的,所以使用unordered_set的话可能要比set快一点。
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result;
unordered_set<int> temp(nums1.begin(),nums1.end());//将num1转换成set。
for(auto num : nums2) {
if(temp.count(num)) result.insert(num);//如果temp中已经有了这个元素则存放在result中
}
return vector<int>(result.begin(),result.end());
}
};
int main() {
Solution s;
vector<int> v1 = {1,2,3,1};
vector<int> v2 = {1,1};
vector<int> res = s.intersect(v1,v2);
for(int num : res) {
cout << num << endl;
}
}