mycode 77.78%
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ def deal(dic,nums): res = [] for item in nums: if item in dic and dic[item]!=0: res.append(item) dic[item] -= 1 return res dic = {} if len(nums1) > len(nums2): for item in nums2: dic[item] = dic.get(item,0) + 1 return deal(dic,nums1) else: for item in nums1: dic[item] = dic.get(item,0) + 1 return deal(dic,nums2)
参考:
1、应用collection.Counter库,可以实现与运算
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ return list((collections.Counter(nums1) & collections.Counter(nums2)).elements())
2、
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ res = [] map = {} for i in nums1: map[i] = map[i]+1 if i in map else 1 for j in nums2: if j in map and map[j] > 0: res.append(j) map[j] -= 1 return res