#349. 两个数组的交集
题目
给定两个数组,求两个数组的交集。注意交集里每一个元素必须是唯一的。
解答
集合解法
- 把两个数组转化成set,去除重复元素。
- 循环更短的set,把其中出现在第二个set里的元素记录在数组中。
class Solution:
def set_intersection(self, set1: Set[int], set2: Set[int]) -> List[int]:
return [x for x in set1 if x in set2]
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set1 = set(nums1)
set2 = set(nums2)
#if set1 is shorter, iterate over set1 to see presence in set2
if len(set1) < len(set2):
return self.set_intersection(set1, set2)
else:
return self.set_intersection(set2, set1)
集合交集解法
将两个数组转化成集合,直接用内置函数返回交集。
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set1 = set(nums1)
set2 = set(nums2)
return list(set1 & set2)
收获
-
set的属性:无序,无重复元素
-
形成数组 – 代码段的运行结构构成了数组
-
[f(x) if condition else g(x) for x in sequence]
-
[f(x) for x in sequence if condition]
-