Doing something you intrinsically are enthusiastic with.

2016年8月24日 星期三

Leetcode-Intersection of Two Arrays

上午8:39 Posted by Unknown No comments
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.

Solution : 
The idea to solve this problem is quite simple.  We can just move all the elements of nums1 to one

container then check every element in nums2 to derive the result. Noted that the result should not 

contain duplicate values. So we can use SET in STL to accomplish this work since the set will ignore

the duplicate values when adding new elements into it.

  1. class Solution {
  2. public:
  3.     vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
  4.        
  5.         set<int> SET (nums1.begin(),nums1.end());
  6.         set<int> result;
  7.        
  8.         for(auto i:nums2)
  9.             if(SET.count(i)) result.insert(i);
  10.        
  11.         return vector<int>(result.begin(), result.end());
  12.        
  13.     }
  14. };


0 意見:

張貼留言