Intersection of Two Arrays II

Intersection of Two Arrays II

dict version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
cnt = {}
res = []
for x in nums1:
cnt[x] = cnt.get(x, 0) + 1
for x in nums2:
if x in cnt and cnt[x] > 0:
res.append(x)
cnt[x] -= 1
return res

Counter version

1
2
3
4
5
6
7
8
9
10
import collections
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
a, b = map(collections.Counter, (nums1, nums2))
return list((a & b).elements())

output

1
2
3
4
In [270]: s = Solution(); t = s.intersect([4,9,5,4], [9,4,9,8,4])
In [271]: t
Out[271]: [9, 4, 4]

leet code