美文网首页北美程序员面试干货
LeetCode 349 [Intersection of Tw

LeetCode 349 [Intersection of Tw

作者: Jason_Yuan | 来源:发表于2016-06-18 16:37 被阅读34次

    原题

    返回两个数组的交

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

    解题思路

    • 方法一:hash map 实现如下
    • 方法二:先把连个数组排序,再merge

    完整代码

    class Solution:
        # @param {int[]} nums1 an integer array
        # @param {int[]} nums2 an integer array
        # @return {int[]} an integer array
        def intersection(self, nums1, nums2):
            # Write your code here
            map = {}
            for x in nums1:
                if x not in map:
                    map[x] = 1
                
            res = []
            for y in nums2:
                if y in map and map[y] == 1:
                    res.append(y)
                    map[y] -= 1
                
            return res
    

    相关文章

      网友评论

        本文标题:LeetCode 349 [Intersection of Tw

        本文链接:https://www.haomeiwen.com/subject/lhfbdttx.html