Leetcode 349:两个数组的交集(最详细解决方案!!!)

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

例子:

给定 num1= [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].

提示:

  • 每个在结果中的元素必定是唯一的。
  • 我们可以不考虑输出结果的顺序。

解题思路

由于问题中的元素是唯一的,所以我们只关心元素的有无,那么我们可以使用set这个结构。首先将nums1的所有数据存入set中,查找nums2中的数据是否在这个set中,如果在的话,我们将这个元素存入一个list里面。

class Solution:
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1 = set(nums1)
        result = set()
        for i in nums2:
            if i in nums1:
                result.add(i)
        return list(result)

一种pythonic的做法

class Solution:
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list(set(nums1) & set(nums2))

我们知道一般set的底层实现是通过平衡二叉树实现的,那么添加元素和搜索元素的时间复杂度都是O(logn)这个级别的,那么上述的算法时间复杂度是O(nlogn)这个级别的。

但是在pythonset的底层实现是通过hash表实现的,所以添加元素和搜索元素的时间复杂度都是O(1)级别的,那么上述的算法时间复杂度是O(n)这个级别的。而空间复杂度依旧是O(n)级别的。如果要使用平衡二叉树的版本,要使用frozenset。因为我们使用了两个set,所以空间复杂度是O(n)级别的。那么我们能不能只是用一个set完成这个问题呢?很简单!!!

class Solution:
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        result = set([i for i in nums1 if i in nums2])
        return list(result)

该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/80564079