Smile&搁浅

知识的积累,只需每天进步一点点!

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.
使用unordered_set    Runtime: 132 ms

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> hs1;
        unordered_set<int> hs2;
        vector<int> vi;
        int len1=nums1.size();
        int len2=nums2.size();
        for(int i=0;i<len1;i++)
            hs1.insert(nums1[i]);
        for(int i=0;i<len2;i++)
            hs2.insert(nums2[i]); 
            
        for(auto it1=hs1.begin();it1!=hs1.end();it1++)
         for(auto it2=hs2.begin();it2!=hs2.end();it2++)
             if(*it1==*it2)
                vi.push_back(*it1);
        
        return vi;
        
    }
};


Runtime: 32 ms


class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> set1;
        int len2=nums2.size();
        for(int i=0;i<len2;i++)
            if(find(nums1.begin(),nums1.end(),nums2[i])!=nums1.end()) 
                set1.insert(nums2[i]);
        return vector<int> (set1.begin(),set1.end());
        
    }
};

Runtime: 8 ms

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> vi;
        unordered_set<int> m(nums1.begin(),nums1.end());
        for(auto a:nums2)
            if(m.count(a))
            {
                vi.push_back(a);
                m.erase(a);
            }
        return vi;
    }
};


排序算法 Runtime: 16 ms

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        std::sort(nums1.begin(),nums1.end());
        std::sort(nums2.begin(),nums2.end());
        vector<int> res;
        int len1=nums1.size();
        int len2=nums2.size();
        int i=0,j=0;
        while(i<len1&&j<len2)
        {
            if(nums1[i]<nums2[j])
                i++;
            else if(nums1[i]>nums2[j])
                j++;
            else
            {
                if(res.empty()||res.back()!=nums1[i])
                    res.push_back(nums1[i]);
                i++;
                j++;
            }
        }
        return res;
    }
};







阅读更多
版权声明:更多请参考:http://blog.csdn.net/yangquanhui1991,我们一起每天进步一点点! https://blog.csdn.net/yangquanhui1991/article/details/51564337
文章标签: Intersection of Two
个人分类: LeetCode
上一篇242. Valid Anagram
下一篇350. Intersection of Two Arrays II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭