卖萌的弱渣

I am stupid, I am hungry.

Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

Solution

(Intersection-of-Two-Arrays.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        hash_map = dict()
        ret = []
        if len(nums1) == 0 or len(nums2) == 0:
            return ret
        for i in range(len(nums1)):
            hash_map[nums1[i]] = i
        for i in nums2:
            if i in hash_map:
                ret.append(i)
                # 以防重复元素添加到ret
                del hash_map[i]
        return ret