每天一算:Intersection of Two Arrays II

leetcode上第350号问题:Intersection of Two Arrays II

给定两个数组,编写一个函数来计算它们的交集。

示例 1:    
输入: nums1 = [1,2,2,1], nums2 = [2,2]    
输出: [2,2]

示例 2:  
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]

说明:

  • 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。

  • 我们可以不考虑输出结果的顺序。

思路

容器类map的使用。

  • 遍历num1,通过map容器record存储num1的元素与频率

  • 遍历num2,在record中查找是否有相同的元素(该元素的存储频率大于0),如果有,用map容器resultVector进行存储,同时该元素的频率减一

动画演示

每天一算:Intersection of Two Arrays II


代码

 1// 350. Intersection of Two Arrays II
2// https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
3// 时间复杂度: O(nlogn)
4// 空间复杂度: O(n)
5class Solution {
6public:
7    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
8
9        map<intint> record;
10        for(int i = 0 ; i < nums1.size() ; i ++){
11             record[nums1[i]] += 1;
12        }
13
14        vector<int> resultVector;
15        for(int i = 0 ; i < nums2.size() ; i ++){
16            if(record[nums2[i]] > 0){
17                resultVector.push_back(nums2[i]);
18                record[nums2[i]] --;
19            }
20        }
21
22        return resultVector;
23    }
24};

执行结果

每天一算:Intersection of Two Arrays II