topic ( link to topic )
Method 1: Hash table
I use a dictionary as a hash table here, generally a list is enough
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
haxi_dict = {
x:0 for x in range(1001)} # 利用字典推导式创建哈希表
result = []
# 字典键对应的值为该数字的出现次数,遍历nums1并修改出现次数
for x in nums1:
haxi_dict[x] += 1
# 遍历nums2并查询字典,如果该对应值的次数大于0,将这个数append到结果数组里,并且字典相应数字的值-1
for y in nums2:
if haxi_dict[y] > 0:
result.append(y)
haxi_dict[y] -= 1
return result
Method 2: counter ( knowledge point reference blog )
application:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
return [i for i in (Counter(nums1)&Counter(nums2)).elements()]
If you can't use it directly, you need to import it first
import collections