def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# sort two arrays
nums1.sort()
nums2.sort()
def is_present(a):
# get the location to insert a into nums2
# on the left of any existing entries
import bisect
i = bisect.bisect_left(nums2, a)
if i < len(nums2) and nums2[i] == a:
nums2.pop(i)
return True
else:
return False
return [a for i, a in enumerate(nums1) if is_present(a)]
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
counts = {}
output = []
# count frequency of each number in nums1
for num in nums1:
counts[num] = counts.get(num, 0) + 1
# check if each number in nums2 has a pair
for num in nums2:
if num in counts and counts[num] > 0:
output.append(num)
counts[num] -= 1
return output