Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
Note:
- Each element in the result must be unique.
- The result can be in any order.
我们使用map来记录nums2中已经出现过的数,然后使用set来记录nums1和nums2中同时出现的数。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
map<int, int> m;
for (int num : nums1) m[num] = 1;
set<int> ans;
for (int num : nums2) {
if (m[num] == 1) ans.insert(num);
}
return vector<int>(ans.begin(), ans.end());
}
};