leetCode 350. Intersection of Two Arrays II 哈希

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?

題目大意:

找出兩個數組中相同元素,相同元素的個數可以大於1.

思路:

將數組2的元素放入multiset中。

遍歷數組1,如果在multiset找到與數組1相等的元素,將該元素放入結果數組中,在multiset中刪除第一個和這個元素相當的元素。

代碼如下:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章