# set集合
# set集合的特点是有序且不重复,找到长度更短列表,
# 依次判断是否共同存在,并添加返回即可。
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set1 = set(nums1)
set2 = set(nums2)
return self.set_intersection(set1, set2)
def set_intersection(self, set1, set2):
if len(set1) > len(set2):
return self.set_intersection(set2, set1)
return [i for i in set1 if i in set2]
方法二:set 集合(简化版)
思路:思路和上面一致,简化了递归思想,并用if大法对边界判断即可。
# set集合(简化版)
# 思路和上面一致,简化了递归思想,并用if大法对边界判断即可。
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set1 = set(nums1)
set2 = set(nums2)
if len(set1) < len(set2):
return [i for i in set1 if i in set2]
else:
return [i for i in set2 if i in set1]