Python解法代码:
class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: nums1.sort() nums2.sort() r = [] i = j = 0 while i < len(nums1) and j < len(nums2): if nums1[i] == nums2[j]: r.append(nums1[i]) i += 1 j += 1 elif nums1[i] < nums2[j]: i += 1 else: j += 1 return r
C++解法代码:
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { if(nums1.size()>nums2.size()) swap(nums1,nums2);//用元素少的数组元素查找 map<int,int> a; for(int i=0;i<nums2.size();i++)//初始化map { if(!a.count(nums2[i])) a.insert(map<int,int>::value_type(nums2[i],1)); else a[nums2[i]]++; } vector<int> res; for(int i=0;i<nums1.size();i++) { if(a.count(nums1[i])) { if(a[nums1[i]]!=0) { res.push_back(nums1[i]); a[nums1[i]]--; } } } return res; } };