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

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

1、時間複雜度爲O(n)的方法
(運行時長爲16ms)

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> vec;
        set<int> nums1Set;
        for(int i : nums1)
        {

            nums1Set.insert(i);
        }
        for(int j : nums2)
        {
            if(nums1Set.find(j)!=nums1Set.end())
            {
                vec.push_back(j);
                nums1Set.erase(j);
            }
        }
        return vec;
    }
};

運行時差長12ms

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> vec;
        set<int> interSet;
        if(nums1.size()==0||nums2.size()==0)
            return vec;
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        for(int i=0,j=0; i<nums1.size()&&j<nums2.size(); )
        {
            if(nums1[i]==nums2[j])
            {
                interSet.insert(nums1[i]);
                j++;
            }
            else if(nums1[i]<nums2[j])
            {
                i++;
            }
            else if(nums1[i]>nums2[j])
            {
                j++;
            }
        }
        for(int i : interSet)
        {
            vec.push_back(i);
        }
        return vec;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章