##四种方式求解:
1 # 给定两个数组,编写一个函数来计算它们的交集 2 3 4 def intersection(nums1, nums2): 5 ''' 6 给定两个数组,编写一个函数来计算它们的交集 7 :param nums1: list 8 :param nums2: list 9 :return: 10 ''' 11 nums1 = set(nums1) 12 nums2 = set(nums2) 13 temp_array = [] 14 for i in nums1: 15 if i in nums2: 16 temp_array.append(i) 17 18 return temp_array 19 20 21 print('_________测试intersection()________________') 22 nums1 = [1, 2, 3, 2, 4, 2] 24 nums2 = [2, 3, 2, 1, 2, 4, 5, 2] 25 temp_array = intersection(nums1, nums2) 26 print("temp_array=", temp_array) 27 28 29 def intersection2(nums1, nums2): 30 ''' 31 方法二 32 :param nums1: 33 :param nums2: 34 :return: 35 ''' 36 temp_array = [] 37 for i in nums1: 38 if i in nums2: 39 if i not in temp_array: 40 temp_array.append(i) 41 return temp_array 42 43 44 print('-----------测试intersection2()-------------') 45 array = intersection2(nums1, nums2) 46 print('array=', array) 47 48 49 def binarySearch(nums, target): 50 ''' 51 二分查找法 52 :param nums: 53 :param target: 54 :return: 55 ''' 56 left = 0 57 right = len(nums) - 1 58 while left <= right: 59 mid = left + (right - left) // 2 60 if nums[mid] == target: 61 return True 62 elif nums[mid] < target: 63 left = mid + 1 64 else: 65 right = mid - 1 66 67 return False 68 69 70 def intersection3(nums1, nums2): 71 ''' 72 73 :param nums1: 74 :param nums2: 75 :return: 76 ''' 77 return set(nums1) & set(nums2) 78 79 80 print('+++++++++测试intersection3()+++++++++++++') 81 array = intersection3(nums1, nums2) 82 print("array=", array) 83 84 85 def intersections4(nums1, nums2): 86 ''' 87 88 :param nums1: 89 :param nums2: 90 :return: 91 ''' 92 nums1 = sorted(nums1) 93 array4 = [] 94 for i in nums2: 95 if i not in array4: 96 if binarySearch(nums1, i): 97 array4.append(i) 98 99 return array4 100 101 102 print("=================测试interSearch()===========") 103 array4 = intersections4(nums1, nums2) 104 print('array4=', array4)
输出:
_________测试intersection()________________ sorted nums1= [1, 2, 2, 2, 3, 4] temp_array= [1, 2, 3, 4] -----------测试intersection2()------------- array= [1, 2, 3, 4] +++++++++测试intersection3()+++++++++++++ array= {1, 2, 3, 4} =================测试interSearch()=========== array4= [2, 3, 1, 4]