两个数组的交集 II

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

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

代码:

思路:

因为是要找相同的数,而且要求重复,可以考虑用一个带有索引的结构来作为中间过渡,这个时候用字典就非常好了

字典用法:https://blog.csdn.net/JNingWei/article/details/78757673

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        list =[]
        dict={}
        for num in nums1:
            if num not in dict:
                dict[num] = 1
            else:
                dict[num] +=1
        for num in nums2:
            if num in dict and dict[num] > 0 :
                dict[num] =dict[num] - 1
                list.append(num)
        return list
原文地址:https://www.cnblogs.com/guangluwutu/p/10623672.html