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.
这个题与349的差不多,不过最后交集的元素如果有多个重复,那么需要保存多个。这个就不能采用set来计算了,因为我们需要计算某个元素共有多少个。例如上述的:nums1中[1,2,2,1]共有两个2,那么每次在另一个数组num2中找到对应的一个2,就需要在num1和num2分别去除一个2。所以我们需要记录当前数组的元素还有多少个。可以使用map结构将其中一个vector转换成map,数组的元素作为map的key,元素的个数作为map的value。然后遍历另一个vector,如果vector的元素在map对应的value不为0,则说明这个元素还有重复的,则加入最后的结果中。
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
unordered_map<int,int> temp;
for(auto num : nums1) {
temp[num]++;
}
for(auto num : nums2) {
if(temp[num]-- > 0) result.push_back(num);
}
return result;
}
};
int main() {
Solution s;
vector<int> v1 = {1,2,3,1};
vector<int> v2 = {1,1};
vector<int> res = s.intersect(v1,v2);
for(int num : res) {
cout << num << endl;
}
}