6 - Easy-两个数组的交集 II

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

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

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

注意:

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

跟进:

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

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        i = 0
        j = 0
        res = []
        while i < len(nums1) and j < len(nums2):
            cur = nums1[i]
            if cur < nums2[j]:
                i += 1
            elif cur == nums2[j]:
                res.append(cur)
                i += 1
                j += 1
            else:
                j += 1
        return res
class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        d = {}
        for i in nums1:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
        r = []
        for i in nums2:
            if i in d and d[i] != 0:
                r.append(i)
                d[i] -= 1
        return r
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容