350. Intersection of Two Arrays II(python)

本文介绍了一种使用哈希表实现的高效列表交集算法。该算法通过遍历第一个列表建立哈希表,再遍历第二个列表查找匹配项,并减少哈希表中计数的方式找到两个列表的公共元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. class Solution(object):  
  2.     def intersect(self, nums1, nums2):  
  3.         """ 
  4.         :type nums1: List[int] 
  5.         :type nums2: List[int] 
  6.         :rtype: List[int] 
  7.         """  
  8.         res = []  
  9.         num = {}  
  10.           
  11.         for c in nums1:  
  12.             num[c] = num[c]+1 if c in num else 1  
  13.           
  14.         for j in nums2:  
  15.             if j in num and num[j]>0:  
  16.                 res.append(j)  
  17.                 num[j]-=1  
  18.                   
  19.         return res  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值