方法一:排序 + 双指针
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
res = []
n1, n2 = len(nums1), len(nums2)
i, j = 0, 0
while i < n1 and j < n2:
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return res
方法二:哈希表
import collections
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dic1 = collections.Counter(nums1)
dic2 = collections.Counter(nums2)
dic = dic1 & dic2
res = []
for i, num in enumerate(dic):
while dic[num] > 0:
res.append(num)
dic[num] -= 1
return res
|