# leetcode-349两个数组的交集

349. 两个数组的交集


简单的set vector使用

#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

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

int main(int argc, char const *argv[]){

int arr1[] = {4,9,5};
int arr2[] = {9,4,8,9,4};
vector<int> nums1(arr1,arr1+sizeof(arr1)/sizeof(int));
vector<int> nums2(arr2,arr2+sizeof(arr2)/sizeof(int));

Solution solution;
vector<int> ans = solution.intersection(nums1,nums2);
int len = ans.size();
for(int i = 0; i < len; i++) cout <<  ans[i] << " ";
cout << endl;

return 0;
}


03-16 1万+

04-28 103
03-22 78
03-03 50
08-21 164
04-24 541
10-14 154
08-22 38
09-04 34
09-30 3282
04-17 1232