给定两个数组,写一个函数来计算它们的交集。
例子:
给定 num1= [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2]
.
本题思路就是把num1 和num2 加入set,代码如下。
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
a = set(nums1)
b = set(nums2)
res =[]
for i in a:
if i in b:
res.append(i)
return res