350. Intersection of Two Arrays II
成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供郊區(qū)網(wǎng)站建設(shè)、郊區(qū)做網(wǎng)站、郊區(qū)網(wǎng)站設(shè)計(jì)、郊區(qū)網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、郊區(qū)企業(yè)網(wǎng)站模板建站服務(wù),十載郊區(qū)做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
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ù)脑亍?/p>
代碼如下:
class Solution { public: vectorintersect(vector & nums1, vector & nums2) { vector result; multiset 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