假设我们有两个数组A和B,这些数组中只有很少的元素。我们必须找到它们的交集。因此,如果A = [1、4、5、3、6],而B = [2、3、5、7、9],则交集将为[3、5]
为了解决这个问题,我们将遵循以下步骤-
取两个数组A和B
如果A的长度小于B的长度,则交换它们
计算数组中元素的频率并将其存储到m
对于B中的每个元素e,如果e以m表示,并且频率不为零,
将频率m [e]降低1
将e插入结果数组
返回结果数组
让我们看下面的实现以更好地理解-
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ m = {} if len(nums1)<len(nums2): nums1,nums2 = nums2,nums1 for i in nums1: if i not in m: m[i] = 1 else: m[i]+=1 result = [] for i in nums2: if i in m and m[i]: m[i]-=1 result.append(i) return result ob1 = Solution()print(ob1.intersect([1,4,5,3,6], [2,3,5,7,9]))
[1,4,5,3,6] [2,3,5,7,9]
输出结果
[3,5]