原题:
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.
找到两个数列都出现的数字,重复数字只输出一遍,一看就感觉是哈希,现在学聪明了打算直接用map,又快又简单,结果:
Success
Runtime: 4 ms, faster than 99.64% of C++ online submissions for Intersection of Two Arrays.
Memory Usage: 9.6 MB, less than 26.27% of C++ online submissions for Intersection of Two Arrays.
代码:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
map<int,int> lib;
for(int i=0;i<nums1.size();i++){
lib[nums1[i]]=1;
}
for(int i=0;i<nums2.size();i++){
if(lib[nums2[i]]==1){lib[nums2[i]]=2;res.push_back(nums2[i]);}
}
return res;
}
};