[LeetCode349] 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.
分类:Hash Table Two Pointers Sort
代码:
1 class Solution { 2 public: 3 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 4 vector<int> res; 5 set<int> hash; 6 7 for(auto num : nums1) 8 hash.insert(num); 9 10 //比较num2与hash中的元素 11 for(auto num : nums2) 12 { 13 auto it = hash.find(num); 14 if(it != hash.end()) 15 { 16 res.push_back(num); 17 hash.erase(num); 18 } 19 } 20 21 return res; 22 } 23 };