您的位置:首页 > 编程语言 > Python开发

[LeetCode][Python]Intersection of Two Arrays

2016-05-19 19:53 661 查看

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,第二个哈希表记录已经在结果中的元素。

class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []; dictionary = {}; addedNum = {}
for num in nums1:
dictionary[num] = True;
for num in nums2:
if dictionary.has_key(num) and not addedNum.has_key(num):
res.append(num);
addedNum[num] = True;
return res;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: