RE . 349. Intersection of Two Arrays

来源:互联网 发布:文字设计软件手机软件 编辑:程序博客网 时间:2024/05/16 09:36

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.

                   简单的 用排序

class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {        vector<int> ans;        //if((nums1.empty()) || (nums2.empty()))       // return nums;        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])            {                if(ans.empty()||nums1[i] != ans[ans.size()-1])   // 如果这里把ans.empty 放到||后面就会报错。  要先检测是否是空!                    ans.push_back(nums1[i]);                ++i;                ++j;            }            else nums1[i]<nums2[j]? i++:j++;                    }        return ans;            }};

                    看不懂的答案。。

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




0 0