題目如下:
給定兩個數組,寫一個方法來計算它們的交集。 例如: 給定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2]. 注意: 輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。 我們可以不考慮輸出結果的順序。 跟進: 如果給定的數組已經排好序呢?你將如何優化你的算法? 如果 nums1 的大小比 nums2 小很多,哪種方法更優? 如果nums2的元素存儲在磁盤上,內存是有限的,你不能一次加載所有的元素到內存中,你該怎么辦?
解題思路:
1.用hash即可。將數組1中元素全部插入到hash列表中,然后對數組2中的每個元素進行查找即可。時間復雜度為O(n),空間復雜度為O(N)。
代碼如下:
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { map<int,int> cnt1; map<int,int> cnt2; vector<int> ret; for(int i = 0;i < nums1.size();++i){ if(cnt1.find(nums1[i])!=cnt1.end()){ cnt1[nums1[i]]++; } else{ cnt1[nums1[i]] = 1; } } for(int i = 0;i < nums2.size();++i){ if(cnt2.find(nums2[i])!=cnt2.end()){ cnt2[nums2[i]]++; } else{ cnt2[nums2[i]] = 1; } } map<int,int>::iterator it1; map<int,int>::iterator it1; for(it1 = cnt1.begin();it1!= cnt1.end();++it1){ it2 = cnt1.find(it1->first); if(it2!=cnt2.end()){ if(it2->second == it1->second){ for(int i = 0;i < it1->second; ++i){ ret.push_back(it1->first); } } } } return ret; } };
2.排序好的數組。對兩個數組排序好的元素依次遍歷即可找到兩個數組中相同的元素。
C++代碼如下:
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); vector<int> res; int l1 = 0; int l2 = 0; while(l1 < nums1.size()&&l2 < nums2.size()){ if(nums1[l1] == nums2[l2]){ res.push_back(nums1[l1]); ++l1; ++l2; }else if(nums1[l1] > nums2[l2]){ ++l2; }else{ ++l1; } } return res; } };