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. 反思

  • 相关阅读:
    NOIP2012 借教室
    bzoj1816 扑克牌
    TYVJ1359 收入计划
    NOIP2015 跳石头
    易错点
    散列表
    数学模板
    12. 17 哈理工网络赛
    哈理工 网络赛
    三角形
  • 原文地址:https://www.cnblogs.com/whl2012/p/5596724.html
Copyright © 2011-2022 走看看