leetcode__两个数组的交集II__python

解题思路:

统计每个单词出现的个数,然后再将其在两个列表中出现的最少的次数找出来,放入这么多个此数字到res中,最后输出结果即可,时间复杂度为O(n)。

具体代码如下:

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dict_one = {}
        dict_two = {}
        for num in nums1:
            if num in dict_one:
                dict_one[num] += 1
            else:
                dict_one[num] = 1
        for num in nums2:
            if num in dict_two:
                dict_two[num] += 1
            else:
                dict_two[num] = 1
        res = []
        for key, value in dict_one.items():
            if key in dict_two.keys():
                times = min(value, dict_two[key])
                for i in range(times):
                    res.append(key)
        return res

你可能感兴趣的:(leetcode,python)