350 Intersection of Two Arrays II 兩個數組的交集 II
阿新 • • 發佈:2018-04-15
intersect 輸出 true res 參考 加載 c++ 排好序 結果
給定兩個數組,寫一個方法來計算它們的交集。
例如:
給定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
註意:
輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。
我們可以不考慮輸出結果的順序。
跟進:
如果給定的數組已經排好序呢?你將如何優化你的算法?
如果 nums1 的大小比 nums2 小很多,哪種方法更優?
如果nums2的元素存儲在磁盤上,內存是有限的,你不能一次加載所有的元素到內存中,你該怎麽辦?
詳見:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
C++:
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int,int> m; vector<int> res; for(int num:nums1) { ++m[num]; } for(int num:nums2) { if(m[num]-->0) { res.push_back(num); } } return res; } };
參考:https://www.cnblogs.com/grandyang/p/5533305.html
350 Intersection of Two Arrays II 兩個數組的交集 II