map————两个数组的交集(2)
1 class Solution { 2 public: 3 vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 4 vector<int> res; 5 vector<int>::iterator iter; 6 if(nums1.size()==0 || nums2.size()==0) return res; 7 for(int i:nums1){ 8 iter = find(nums2.begin(),nums2.end(),i); 9 if(iter!=nums2.end()){ 10 res.push_back(i); 11 nums2.erase(iter); 12 } 13 else continue; 14 } 15 return res; 16 } 17 };
map方法:更快
1 class Solution { 2 public: 3 vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 4 map<int,int> cun; 5 for(int i:nums1){ 6 if(!cun.count(i)) cun.insert(map<int,int>::value_type(i,1)); 7 else cun[i]++; 8 } 9 vector<int> res; 10 for(int i:nums2){ 11 if(cun.count(i)){ 12 if(cun[i]!=0){ 13 cun[i]--; 14 res.push_back(i); 15 } 16 } 17 } 18 return res; 19 } 20 };