leetcode350之实现求解两数组交集(包含重复元素)
2021-01-04 22:28
标签:set leetcode 一个 etc sort == class targe 次数 给定两个数组,编写一个函数来计算它们的交集。 说明: 输出: leetcode350之实现求解两数组交集(包含重复元素) 标签:set leetcode 一个 etc sort == class targe 次数 原文地址:https://www.cnblogs.com/rounie/p/12983886.html
1 def binarySearch(nums, target):
2 ‘‘‘
3 在数组中二分查找指定元素
4 :param nums:
5 :param target:
6 :return:
7 ‘‘‘
8 left, right = 0, len(nums) - 1
9 while left right:
10 mid = left + (right - left) // 2
11 if nums[mid] == target:
12 return True
13 elif nums[mid] target:
14 left = mid + 1
15 else:
16 right = mid - 1
17
18 return False
19
20
21 def intersect1(num1, num2):
22 ‘‘‘
23 求两个列表交集元素
24 :param num1:
25 :param num2:
26 :return:
27 ‘‘‘
28 array1 = []
29 num1 = sorted(num1)
30 for i in num2:
31 if binarySearch(num1, i):
32 array1.append(i)
33 num1.remove(i)
34 array1 = sorted(array1)
35
36 return array1
37
38
39 print("==========测试intersect()==========")
40 nums1 = [1, 3, 1, 2, 4, 2]
41 nums2 = [4, 8, 1, 2, 1, 3, 8, 2]
42 array1 = intersect1(nums1, nums2)
43 print("array1=", array1)
44
45
46 def intersect2(nums1, nums2):
47 ‘‘‘
48
49 :param nums1:
50 :param nums2:
51 :return:
52 ‘‘‘
53 array2 = []
54 temp_array2 = set(nums1) & set(nums2) # temp_array2 is a set
55 for i in temp_array2:
56 array2 += [i] * min(nums1.count(i), nums2.count(i))
57 return array2
58
59
60 print("+++++++++++测试intersect2()+++++++++++++")
61 array2 = intersect2(nums1, nums2)
62 print("array2=", array2)
63
64
65 def intersect3(nums1, nums2):
66 ‘‘‘
67
68 :param nums1:
69 :param nums2:
70 :return:
71 ‘‘‘
72 array3 = []
73 for i in nums1:
74 if i in nums2:
75 array3.append(i)
76 nums2.remove(i)
77 array3 = sorted(array3)
78 return array3
79
80
81 print("----------------测试intersect3()-----------")
82 array3 = intersect3(nums2, nums1)
83 print("array3=", array3)
==========测试intersect()==========
array1= [1, 1, 2, 2, 3, 4]
+++++++++++测试intersect2()+++++++++++++
array2= [1, 1, 2, 2, 3, 4]
----------------测试intersect3()-----------
array3= [1, 1, 2, 2, 3, 4]
文章标题:leetcode350之实现求解两数组交集(包含重复元素)
文章链接:http://soscw.com/index.php/essay/40122.html