zoukankan      html  css  js  c++  java
  • 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. 反思

  • 相关阅读:
    译:DOM2中的高级事件处理(转)
    Cookbook of QUnit
    URI编码解码和base64
    css截断长文本显示
    内置对象,原生对象和宿主对象
    HTML中的meta(转载)
    iframe编程的一些问题
    自动补全搜索实现
    new的探究
    深入instanceof
  • 原文地址:https://www.cnblogs.com/whl2012/p/5596724.html
Copyright © 2011-2022 走看看