MDGSF Software Engineer

[算法学习][leetcode] 349 Intersection of Two Arrays

2017-09-05
mdgsf
Art

https://leetcode.com/problems/intersection-of-two-arrays/description/

题目

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.

题目翻译

题目解析

参考答案

#include <iostream>
#include <vector>
#include <set>
using namespace std;

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
    {
        set<int> setNum1(nums1.begin(), nums1.end());
        set<int> setNum2(nums2.begin(), nums2.end());
        set<int> setResult;

        set<int>::iterator iter = setNum1.begin();
        while (iter != setNum1.end())
        {
            set<int>::iterator iter2 = setNum2.find(*iter);
            if (iter2 != setNum2.end())
            {
                setResult.insert(*iter);
            }
            ++iter;
        }

        vector<int> vecResult(setResult.begin(), setResult.end());
        return vecResult;
    }
};

int main()
{
    vector<int> nums1 = { 1, 2, 2, 3 };
    vector<int> nums2 = { 2, 2 };
    vector<int> vecResult;

    Solution o;
    vecResult = o.intersection(nums1, nums2);

    return 0;
}

weixingongzhonghao

Similar Posts

下一篇 [Git] git add

Comments