溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

leetCode 350. Intersection of Two Arrays II 哈希

發(fā)布時(shí)間:2020-07-02 09:47:44 來(lái)源:網(wǎng)絡(luò) 閱讀:826 作者:313119992 欄目:編程語(yǔ)言

350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.

  • The result can be in any order.


Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?

  • What if nums1's size is small compared to nums2's size? Which algorithm is better?

  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

題目大意:

找出兩個(gè)數(shù)組中相同元素,相同元素的個(gè)數(shù)可以大于1.

思路:

將數(shù)組2的元素放入multiset中。

遍歷數(shù)組1,如果在multiset找到與數(shù)組1相等的元素,將該元素放入結(jié)果數(shù)組中,在multiset中刪除第一個(gè)和這個(gè)元素相當(dāng)?shù)脑亍?/span>

代碼如下:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        multiset<int> set2;
        for(int i = 0; i < nums2.size(); i++)
            set2.insert(nums2[i]);
        for(int i = 0; i < nums1.size(); i++)
        {
            if(set2.find(nums1[i]) != set2.end())
            {
                result.push_back(nums1[i]);
                set2.erase(set2.find(nums1[i]));
            }
        }
        return result;
    }
};

2016-08-13 14:03:35

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI