给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
代码:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
a=nums1
a=sorted(a)
b=nums2
b=sorted(b)
i=0
j=0
c=[]
while i<len(a) and j<len(b):
if a[i]==b[j]:
if a[i] not in c:
c.append(a[i])
i+=1
j+=1
elif a[i]<b[j]:
i+=1
else:
j+=1
return c
题目来源:力扣(LeetCode)