[每日LeetCode] 349. Intersection of Two Arrays

  |   0 评论   |   218 浏览

原文链接 [每日LeetCode] 349. Intersection of Two Arrays

Description:

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

思路:本题要求两个数组的交集,比较简单,根据set集合自由排序的特性,把一个数组中的数存到set集合中,然后遍历另一个数组,若在set中存在则加入到res数组中。另外看到有基于STL中set_intersection函数实现的,set_intersection的函数原型为:std::set_intersection(std::begin(words1), std::end(words1), std::begin(words2), std::end(words2),std::inserter(result, std::begin(result))); ,在此记录一下其用法。


C++代码(set实现)

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> s(nums1.begin(), nums1.end()), res;
        for (auto a : nums2) {
            if (s.count(a)) 
                res.insert(a);
        }
        return vector<int>(res.begin(), res.end());
    }
};

运行时间:8ms

运行内存:9.6M


C++代码(STL set_intersection实现)

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> s1(nums1.begin(), nums1.end()), s2(nums2.begin(), nums2.end()), res;
        set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(res, res.begin()));
        return vector<int>(res.begin(), res.end());
    }
};

运行时间:8ms

运行时间:10.6M

评论

发表评论