[LeetCode]349. Intersection of Two Arrays

来源:互联网 发布:mac版qq接收文件 编辑:程序博客网 时间:2024/05/21 08:45

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].

代码

#include <algorithm>#include <iostream>#include <vector>#include <set>using namespace std;class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {        sort(nums1.begin(),nums1.end());        sort(nums2.begin(),nums2.end());        set<int> tmp;        int p1 = 0;        int p2 = 0;        while(p1 < (int)nums1.size() && p2 < (int)nums2.size())        {            if(nums1[p1] == nums2[p2])            {                tmp.insert(nums1[p1]);                p1++;                p2++;            }            else if(nums1[p1] > nums2[p2])                p2++;            else                p1++;        }        int n = tmp.size();        vector<int> nums3(n);        copy(tmp.begin(),tmp.end(),nums3.begin());        return nums3;    }};

代码分析

此题要求寻找两个数的交集,并且最后的vector容器不能有重复元素。
我的想法就是直接用set容器保存,这样就不可能有重复元素。
然后再转换成vector。

然后自己还是太naive了,copy()函数得准确使用

copy(begin,end,container.begin());//被复制的容器需事先分配足够的空间,不然无法复制进去

其他解法

可以到下述网址查看
https://leetcode.com/problems/intersection-of-two-arrays/discuss/

原创粉丝点击