349. Intersection of Two Arrays

1. 问题描述

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.
Tags: Binary Search Hash Table Two Pointers Sort

Similar Problems: (E) Intersection of Two Arrays II

2. 解题思路

  • 求两个数组中公有的数字
  • 利用STL中的集合SET实现

3. 代码

 1 class Solution {
 2 public:
 3     vector<int> intersection(vector<int>& nums1, vector<int>& nums2) 
 4     {
 5         std::vector<int> tVec;
 6         if (nums1.empty() || nums2.empty())
 7         {
 8             return tVec;
 9         }
10         std::set<int> tSet;
11         std::set<int> tResultSet;
12         for (int i=0; i<nums1.size(); i++)
13         {
14             tSet.insert(nums1.at(i));
15         }
16         for (int i=0; i<nums2.size(); i++)
17         {
18             if (tSet.find(nums2.at(i)) != tSet.end())
19             {
20                 tResultSet.insert(nums2.at(i));
21             }
22         }
23         std::set<int>::iterator it; 
24         for(it = tResultSet.begin(); it != tResultSet.end(); it++)  
25         {  
26             tVec.push_back(*it); 
27         }  
28         return tVec;        
29     }
30 };

4. 反思

posted on 2016-06-18 19:27  whl-hl  阅读(158)  评论(0编辑  收藏  举报

导航