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)
return i < len(nums2) and nums2[i] == a
return [
a for i, a in enumerate(nums1)
if is_present(a) and (i == 0 or a != nums1[i-1])
]
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# sort two arrays
nums1.sort()
nums2.sort()
# two pointers
p1, p2 = 0, 0
output = []
while p1 < len(nums1) and p2 < len(nums2):
if nums1[p1] > nums2[p2]:
p2 += 1
elif nums1[p1] < nums2[p2]:
p1 += 1
else:
if len(output) == 0 or nums1[i] != output[-1]:
output.append(nums1[i])
p1 += 1
p2 += 1
return output
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] = 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