Leetcode:350. 两个数组的交集 II(Python 3)

题目:

两个数组的交集 II

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

例如:
给定 nums1 = [1, 2, 2, 1]nums2 = [2, 2], 返回 [2, 2].

注意:

  •    输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
  •    我们可以不考虑输出结果的顺序。

跟进:

  • 如果给定的数组已经排好序呢?你将如何优化你的算法?
  • 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
  • 如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办?

解答:

简单题。

1. 暴力求解:

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        result = []
        for i in nums1:
            if i in nums2:
                result.append(i)
                nums2.remove(i)
                    
        return result
                    

O(n^{2})的时间复杂度,并不好。

2. 题目给了提示,如果这两个数组已经排序,那么只需要一次循环就可以了。

于是,可以先排序,再用一次循环找到结果

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        result = []
        i = 0
        j = 0
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                result.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return result
            

时间复杂度就是排序的O(nlogn)

3. 能否在O(n)内完成?

考虑一下hash表,这个东西在Python里面是数据类型dict,将nums1的元素存入dict,然后从dict中查找nums2的元素即可。

dict放什么东西?key为nums1的值,value为这个值出现的次数。

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        if not nums1 or not nums2:
            return []
        result = []
        dict1 = dict()
        for i in nums1:
            if i not in dict1:
                dict1[i] = 1
            else:
                dict1[i] += 1
        for i in nums2:
            if i in dict1:
                if dict1[i] > 0:
                    result.append(i)
                    dict1[i] -= 1
        return result

4. 更简洁的代码(又是别人家的,这家是Python 2):

class Solution(object):
    def intersect(self, nums1, nums2):

        counts = collections.Counter(nums1)
        res = []

        for num in nums2:
            if counts[num] > 0:
                res += num,
                counts[num] -= 1

        return res

这里直接用了Python的built-in,省的自己建一个dict

代码来自https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82247/Three-Python-Solutions

5. 还有一行代码搞定的:

def intersect(self, nums1, nums2):
    return list((collections.Counter(nums1) & collections.Counter(nums2)).elements())

discuss区的大牛真的多。

参见https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82269/Short-Python-C++

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值