代碼題(21)— 兩數組交集

來源:互聯網
上載者:User

標籤: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)— 兩數組交集

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.