leetcode-数组-两个数组的交集 II|Intersection of Two Arrays II(Python3)

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

例如:

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

注意:

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

跟进:

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

代码

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        dic = dict()
        for i in nums1:
            if i in dic:
                dic[i] += 1
            else:
                dic[i] = 1

        n = list()
        for i in nums2:
            if i in dic.keys() and dic[i] != 0:
                dic[i] -= 1
                n.append(i)
        return n

if __name__ == '__main__':
    s = Solution()
    a = s.intersect([1,2,2,3],[2,2])
    print(a)

你可能感兴趣的:(leetcode-数组-两个数组的交集 II|Intersection of Two Arrays II(Python3))