LeetCode 350 [Intersection of Two Array II]

原题

计算两个数组的交
注意事项
每个元素出现次数得和在数组里一样答案可以以任意顺序给出

样例
nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].

解题思路

  • 遍历第一个数组,构建hash map,计数
  • 遍历第二个数组,如果存在在hash map而且个数大于零,加入res数组
  • 其他方法:先排序,两根指针

完整代码

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        map = {}
        for x in nums1:
            if x not in map:
                map[x] = 1
            else:
                map[x] += 1
            
        res = []
        for y in nums2:
            if y in map and map[y] > 0:
                res.append(y)
                map[y] -= 1
            
        return res

你可能感兴趣的:(LeetCode 350 [Intersection of Two Array II])