[LeetCode][Python]Intersection of Two Arrays

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.

https://leetcode.com/problems/intersection-of-two-arrays/

 

 


 

 

求两个数组的交集。

先遍历nums1,第一个哈希表记录所有nums1中出现过的元素。

再遍历nums2,第二个哈希表记录已经在结果中的元素。

 

 1 class Solution(object):
 2     def intersection(self, nums1, nums2):
 3         """
 4         :type nums1: List[int]
 5         :type nums2: List[int]
 6         :rtype: List[int]
 7         """
 8         res = []; dictionary = {}; addedNum = {}
 9         for num in nums1:
10             dictionary[num] = True;
11         for num in nums2:
12             if dictionary.has_key(num) and not addedNum.has_key(num):
13                 res.append(num);
14                 addedNum[num] = True;
15         return res;

 

posted @ 2016-05-19 19:53  `Liok  阅读(523)  评论(0编辑  收藏  举报