350. Intersection of Two Arrays II & Add to List 349. Intersection of Two Arrays 笔记

  1. 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].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
返回两个数组的公共元素,要是相同的有多个就返回多个。用一个哈希表统计第一个数组的每个数的个数,遍历第二个数组,哈希表里头有就保存到结果,并把哈希表里的这个数的个数减1。
代码如下:

class Solution {
public:
    vector intersect(vector& nums1, vector& nums2) {
        unordered_map m;
        vector res;
        for(int i = 0; i < nums1.size(); i++)
        {
            m[nums1[i]]++;
        }
        for(int i = 0; i < nums2.size(); i++)
        {
            m[nums2[i]]--;
            if(m[nums2[i]] >= 0)
                res.push_back(nums2[i]);
        }
        return res;
    }
};
  1. Intersection of Two Arrays
    和上边的区别是重复的元素只输出一次。
    就在遍历第二个数组的时候,输出这个之后把哈希表里这个
    数的值置为0就行了。
    代码如下:
class Solution {
public:
    vector intersection(vector& nums1, vector& nums2) {
        unordered_map m;
        vector res;
        for(int i = 0; i < nums1.size(); i++)
        {
            m[nums1[i]]++;
        }
        for(int i = 0; i < nums2.size(); i++)
        {
            m[nums2[i]]--;
            if(m[nums2[i]] >= 0)
            {
                res.push_back(nums2[i]);
                m[nums2[i]] = 0;
            }
        }
        return res;
        }
};

你可能感兴趣的:(350. Intersection of Two Arrays II & Add to List 349. Intersection of Two Arrays 笔记)