返回两个数组的交
注意事项
- Each element in the result must be unique.
- The result can be in any order.
样例
nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2]
.
挑战
可以用三种不同的方法实现吗?
class Solution {
public:
/*
* @param nums1: an integer array
* @param nums2: an integer array
* @return: an integer array
*/
vector<int> intersection(vector<int> nums1, vector<int> nums2) {
// write your code here
vector<int> result;
map<int,int> hash;
for(int i=0;i<nums1.size();i++){
if(!hash.count(nums1[i]))
hash[nums1[i]]=1;
}
for(int i=0;i<nums2.size();i++){
if(hash.count(nums2[i])){
if(hash[nums2[i]]++==1){
result.push_back(nums2[i]);
}
}
}
return result;
}
};