Intersection of Two Arrays I II

来源:互联网 发布:windows smb访问 编辑:程序博客网 时间:2024/06/11 10:20

Intersection of Two Arrays I

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
返回不允许重复!

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

Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
返回允许重复!

class Solution {public:    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {        unordered_map<int,int> mp;        for(auto& num:nums1){            ++mp[num];        }        vector<int >res;        for(auto& num:nums2){            if(mp[num]>0){                res.push_back(num);                mp[num]--;            }        }        return res;    }};
0 0
原创粉丝点击