LeetCode - 两个数组的交集 I

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

例子:

给定 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

一种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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

我们知道一般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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值