首页 > 其他 > 详细

349. Intersection of Two Arrays

时间:2018-10-30 23:36:09      阅读:186      评论:0      收藏:0      [点我收藏+]

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

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

AC code:

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size();
        int len2 = nums2.size();
        vector<int> ans;
        map<int, int> mp;
        if (len1 == 0 || len2 == 0) return ans;
        for (int i = 0; i < len1; ++i) {
            mp[nums1[i]] = 1;
        }
        for (int i = 0; i < len2; ++i) {
            if (mp[nums2[i]] == 1) {
                ans.push_back(nums2[i]);
                mp[nums2[i]]--;
            }
        }
        return ans;
    }
};

  

 

349. Intersection of Two Arrays

原文:https://www.cnblogs.com/ruruozhenhao/p/9880043.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!