您的位置:首页 > 脚本大全 > > 正文

python用指针合并两个有序数组(Python3实现计算两个数组的交集算法示例)

更多 时间:2021-10-22 07:40:26 类别:脚本大全 浏览量:251

python用指针合并两个有序数组

Python3实现计算两个数组的交集算法示例

本文实例讲述了python3实现计算两个数组的交集算法。分享给大家供大家参考,具体如下:

问题:

给定两个数组,写一个方法来计算它们的交集。

方案一:利用collections.counter&运算,一步到位,找到 最小次数 的相同元素。

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • # -*- coding:utf-8 -*-
  • #! python3
  • def intersect(nums1, nums2):
  •   """
  •   :type nums1: list[int]
  •   :type nums2: list[int]
  •   :rtype: list[int]
  •   """
  •   import collections
  •   a, b = map(collections.counter, (nums1, nums2))
  •   return list((a & b).elements())
  • #测试
  • arr1 = [1,2,3,4,5]
  • arr2 = [3,4,5,6,7]
  • print(intersect(arr1,arr2))
  • 运行结果:

    [3, 4, 5]

    方案二:遍历其中一个数组,发现相同元素时添加到新列表中,同时删去另一个数组中的一个相同元素

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • # -*- coding:utf-8 -*-
  • #! python3
  • def intersect(nums1, nums2):
  •   """
  •   :type nums1: list[int]
  •   :type nums2: list[int]
  •   :rtype: list[int]
  •   """
  •   res = []
  •   for k in nums1:
  •     if k in nums2:
  •       res.append(k)
  •       nums2.remove(k)
  •   return res
  • #测试
  • arr1 = [1,2,3,4,5]
  • arr2 = [3,4,5,6,7]
  • print(intersect(arr1,arr2))
  • 运行结果:

    [3, 4, 5]

    希望本文所述对大家python程序设计有所帮助。

    原文链接:https://blog.csdn.net/zhenghaitian/article/details/80896392

    您可能感兴趣