Intersection of Two Arrays 两数组的交

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

Example: Givennums1=[1, 2, 2, 1],nums2=[2, 2], return[2].

Note:

  • Each element in the result must be unique.

  • The result can be in any order.

python 自带功能:

    def intersection(self, nums1, nums2):
        return list(set(nums1) & set(nums2))

自己写个程序实现集合的交集功能:

    def intersection(self, nums1, nums2):
        s = set(nums1)
        result = set()        # 做成 set,避免重复元素
        for n in nums2:
            if n in s:
                result.add(n)

        return list(result)   # 题目要求返回数组,所以转回list

这样写也行

    def intersection(self, nums1, nums2):
        s = set(nums1)
        result = []          #直接做成 list
        for n in nums2:
            if n in s:
                result.append(n)
                s.remove(n)  # 在原来的集合里删掉n,避免 n 被重复放入 result

        return result

以上都是 O(N + M)。

还可以把两个数组排序后用2根指针,这是 O(NlogN)

还有可以用2分法。排序一个数组,然后在这个数组里面找另外一个数组的数

Last updated

Was this helpful?