標籤:turn homepage 映射 pre bsp ref ++ class www.
1、349. 兩個數組的交集
給定兩個數組,寫一個函數來計算它們的交集。
例子:
給定 num1= [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].
提示:
- 每個在結果中的元素必定是唯一的。
- 我們可以不考慮輸出結果的順序。
這道題讓我們找兩個數組交集的部分(不包含重複數字),難度不算大,我們可以用個set把nums1都放進去,然後遍曆nums2的元素,如果在set中存在,說明是交集的部分,加入結果的set中,最後再把結果轉為vector的形式即可:
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> res; if(nums1.empty() || nums2.empty()) return res; unordered_set<int> s(nums1.begin(), nums1.end()); unordered_set<int> temp; for(int val : nums2) { if(s.count(val)) temp.insert(val); } return vector<int>(temp.begin(), temp.end()); }};
2、350. 兩個數組的交集 II
給定兩個數組,寫一個方法來計算它們的交集。
例如:
給定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
注意:
- 輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。
- 我們可以不考慮輸出結果的順序。
這道題是之前那道Intersection of Two Arrays的拓展,不同之處在於這道題允許我們返回重複的數字,而且是儘可能多的返回,之前那道題是說有重複的數字只返回一個就行。那麼這道題我們用雜湊表來建立nums1中字元和其出現個數之間的映射, 然後遍曆nums2數組,如果當前字元在雜湊表中的個數大於0,則將此字元加入結果res中,然後雜湊表的對應值自減1,
class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> res; if(nums1.empty() || nums2.empty()) return res; unordered_map<int, int> m; for(int val : nums1) m[val]++; for(int val : nums2) { if(m[val] > 0) { m[val]--; res.push_back(val); } } return res; }};
代碼題(21)— 兩數組交集