给定两个数组,编写一个函数来计算它们的交集。(前面两个是我写的,后面两个抄的)
class Solution(object):
def intersect0(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set(nums2)
iter_ = set1 & set2
ret_dict1 = self.count(nums1)
ret_dict2 = self.count(nums2)
ret_list = []
for item in iter_:
if item in ret_dict1 and item in ret_dict2:
ret_list.extend([item] * min(ret_dict1[item], ret_dict2[item]))
return ret_list
def count(self, nums):
ret_dict = {}
for item in nums:
count = ret_dict.get(item, 0)
ret_dict[item] = count + 1
return ret_dict
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set(nums2)
iter_ = set1 & set2
ret_list = []
for item in iter_:
ret_list.extend([item]*min(nums1.count(item), nums2.count(item)))
return ret_list
def intersect1(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
nums1_dict = {}
for item in nums1:
nums1_dict.setdefault(item, 0)
nums1_dict[item] += 1
for item2 in nums2:
if nums1_dict.get(item2, 0) > 0:
result.append(item2)
nums1_dict[item2] -= 1
return result
def intersect2(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
i, j = 0, 0
res = []
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return res
if __name__ == ‘__main__‘:
s = Solution()
nums1 = [1, 2, 2, 1]; nums2 = [2, 2]
# nums1 = [4, 9, 5]; nums2 = [9, 4, 9, 8, 4]
print(s.intersect(nums1, nums2))
原文:https://www.cnblogs.com/liuzhanghao/p/14214862.html