Python :compute two arrays‘ intersection

本文介绍了一种计算两个数组交集的算法,通过实例展示了输入输出情况,并探讨了不同情况下算法的优化策略,包括已排序数组、大小差异显著的数组以及大规模数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two arrays, write a function to compute their intersection.

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

EX1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

EX2: 

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
  • 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
  • 我们可以不考虑输出结果的顺序。

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
  • 如果给定的数组已经排好序呢?你将如何优化你的算法?
  • 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
  • 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

Sol One

If two arrays 's numbers arent too big, and for the big size of arrays, there is no doubt that the idea of #COUNTING-SORT will preform really well.

毫无疑问,如果对于数字较小,而规格大的数组,用#COUNTING-SORT类似的方法是可以表现得非常棒!

Here is the code:

class Solution(object):
    def intersect(self, nums1, nums2):
        k=10
        C=[]
        B=[]
        for i in range(k):
            C.append(0)
        for j in range(len(nums1)):
            C[nums1[j]-1]=C[nums1[j]-1]+1
        for j in range(len(nums2)):
            if C[nums2[j]-1]>0:
                B.append(nums2[j])
                C[nums2[j]-1]=C[nums2[j]-1]-1
        return B

Sol Two:

But when the number is bigger than 10**3, it becomes really too big to  run.

Here s the general solution.

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        record, result = {}, []
        for num in nums1:
            record[num] = record.get(num, 0) + 1
                
        for num in nums2:
            if num in record and record[num]:
                result.append(num)
                record[num] -= 1
        return result

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值