LeetCode 349 [Intersection of Two Array]

原题

返回两个数组的交

样例
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 Two Array])