解法是使用字典保存nums1和其计数,再遍历nums2即可
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
v1 = {}
for n1 in nums1:
try:
v1[n1] += 1
except:
v1[n1] = 1
result = []
for n2 in nums2:
try:
v1[n2] -= 1
result.append(n2)
if v1[n2] == 0:
v1.pop(n2)
except:
pass
return result