码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Python]Intersection of Two Arrays

时间:2016-05-19 21:03:20      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

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;

 

[LeetCode][Python]Intersection of Two Arrays

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/5509900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!