给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
代码如下:
class Solution(object):
def intersect(self, nums1, nums2):
count1=Counter(nums1)
count2=Counter(nums2)
intersect=[]
for key in count1:
if key in count2:
intersect+=[key]*min(count1[key],count2[key])
return intersect
Counter用法(计数器):
范例:
from collections import Counter
#统计词频
nums=[1,2,3,3,4,2,1,2,1]
num=Counter(nums)
print(num)
#转换成列表
list=list(num.elements())
print(list)
结果:
Counter({1: 3, 2: 3, 3: 2, 4: 1})
[1, 1, 1, 2, 2, 2, 3, 3, 4]