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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容