[leetcode]349.Intersection of Two Arrays

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]349.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.

Subscribe to see which companies asked this question

 

Solution:

 1 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) 
 2     {
 3         unordered_set<int> htable;
 4         unordered_set<int> htmp;
 5         vector<int> ret;
 6         
 7         for (int i = 0; i < (int)nums1.size(); i++)
 8             htable.insert(nums1[i]);
 9         
10         for (int i = 0; i < (int)nums2.size(); i++)
11             if (htable.find(nums2[i]) != htable.end())
12                 htmp.insert(nums2[i]);
13         
14         for (auto it = htmp.begin(); it != htmp.end(); ++it)
15             ret.push_back(*it);
16         
17         return ret;
18     }

 

以上是关于[leetcode]349.Intersection of Two Arrays的主要内容,如果未能解决你的问题,请参考以下文章

如何做LeetCode

leetcode可以写在简历上吗

[Leetcode]leetcode1-10题随记

leetcode分类刷题(续2)

leetcode分类刷题

LintCode,hihoCoder,LeetCode有啥区别