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.

My solution

  • 自然的想法是把nums1的每个数和nums2的每个数对比,复杂度为O(nm).如果排好序的呢? 那就是nlgn和mlgm,一般情况下这个方式更小一点.
  • 考虑到有很多重复数字, 并且问题的根本在于判断"共有元素",所以很容易联想到python方式, 把数组专为set,用 in / not in判断.没看过源码,也不知道这个过程复杂度是怎样的 ==
    下为先排序的方式:
class Solution {
public:
    vector<int> intersection(vector<int> &nums1, vector<int> &nums2) {
        vector<int> res;
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int i = 0, j = 0;
        while (i < nums1.size() && j < nums2.size()) {
            if (nums1[i] < nums2[j]) ++i;
            else if (nums1[i] > nums2[j]) ++j;
            else {
                res.push_back(nums1[i]);
                ++i;
                ++j;
                while (nums1[i] == nums1[i - 1]) ++i;
                while (nums2[j] == nums2[j - 1]) ++j;
            }
        }
        return res;
    }
};

Discuss

using c++ set

vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    set<int> s(nums1.begin(), nums1.end());
    vector<int> out;
    for (int x : nums2)
        if (s.erase(x))
            out.push_back(x);
    return out;
}

急需看完c++ primer 啊!!

Reference


xufeng
8 声望3 粉丝

有多少人工就有多少智能