LeetCode数组-350.两个数组的交集||

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

示例 1:

输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]

示例 2:

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]

Python:

    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        my_dict = {}

        for value in nums1:
            if not value in my_dict:
                my_dict[value] = 1
            else:
                my_dict[value] += 1
        for num in nums2:
            if num in my_dict and my_dict[num] >= 1:
                my_dict[num] -=1
                res.append(num)
        return res

猜你喜欢

转载自blog.csdn.net/HarderFortunate/article/details/82957927