码迷,mamicode.com
首页 > 其他好文 > 详细

349. Intersection of Two Arrays

时间:2018-10-31 00:00:59      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:unique   amp   array   example   vector   inpu   pre   order   com   

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

标签:unique   amp   array   example   vector   inpu   pre   order   com   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!