349. Intersection of Two Arrays

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

Thoughts

找两个数组中的交集,每个交集元素值只保留一次。用hash set存下一个数组的所有元素然后遍历另一个数组当遇到在set里的就插入到结果,并为了去重再在set中删去对应元素。

/*
 * @lc app=leetcode id=349 lang=cpp
 *
 * [349] Intersection of Two Arrays
 */

// @lc code=start
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> s(nums1.begin(), nums1.end());
        vector<int> res;
        for (const auto num : nums2) {
            if (s.count(num)) {
                res.push_back(num);
                s.erase(num);
            }
        }
        return res; 
    }
};
// @lc code=end

假设已经排好序. 两个指针指向两个数组的头, 依次往前走就好.

Code

Analysis

不算排序的话时间复杂度O(N).

Last updated

Was this helpful?