Topic
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 of the element in the result should appear as many times as it shows in both arrays.
The result can be as any order.
the
The intersection of two arrays, which contains the maximum number of occurrences of each number in the intersection as much as possible. Solving
Ideas and 349 ideas the same http://blog.csdn.net/xunalove/article/details/79372497, but not to heavy, while Nums1[i] in Nums2, delete nums2 in a nums1[i] Elements. The Python code is implemented. However, in C + + vector, remove () is the deletion of all equal to Nums1[i in nums2, not desirable.
Therefore, another method is used to save the number of occurrences of each number in the NUMS1 by using the map, traversing nums2 and processing. C + + code
Class Solution {public
:
vector<int> intersect (vector<int>& nums1, vector<int>& NUMS2) {
vector<int>res;
map<int,int>m;
for (int i=0; i<nums1.size (); i++)
{
m[nums1[i]]++;
}
for (int i=0; i<nums2.size (); i++)
{
if (m[nums2[i]]>0)
{
res.push_back (nums2[i));
m[nums2[i]]--
}
}
return res;
}
;
Python code
Class Solution (object):
def intersect (self, NUMS1, NUMS2): ""
: Type Nums1:list[int]
: type NUMS2: List[int]
: rtype:list[int]
""
res = []
for I in range (0, Len (nums1)):
if Nums1[i] in NUMS2:
Res.append (Nums1[i])
nums2.remove (Nums1[i]) #删除nums2中该数
If Len (nums2) ==0 or Len (nums1) ==0:
return Res return
Res
Python code is simpler