zoukankan      html  css  js  c++  java
  • Leetcode题目: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.

    题目解答:

    So easy~求两个数组的交集,太简单了,不赘述,直接看代码。

    代码:

    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            sort(nums1.begin(), nums1.end());
            vector<int>::iterator end_unique =  unique(nums1.begin(), nums1.end()); 
            nums1.erase(end_unique, nums1.end());
            sort(nums2.begin(),nums2.end());
            end_unique =  unique(nums2.begin(), nums2.end()); 
            nums2.erase(end_unique, nums2.end());
            vector<int>::iterator nit1 = nums1.begin();
            vector<int>::iterator nit2 = nums2.begin();
            vector<int> res;
            while((nit1 != nums1.end())  && (nit2 != nums2.end()) )
            {
                if(*nit1 == *nit2)
                {
                    res.push_back(*nit1);
                    nit1++;
                    nit2++;
                }
                else if(*nit1 < *nit2)
                {
                    nit1++;
                }
                else
                {
                    nit2++;
                }
                
            }
        return res;
        }
    };
    

      

  • 相关阅读:
    3.14周末作业
    3.13作业
    文件处理
    字符编码
    基本数据类型总结
    基本数据类型--------------------集合set()
    python入门009
    作业009
    python入门008
    作业008
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5542488.html
Copyright © 2011-2022 走看看