[LeetCode][Python]Intersection of Two Arrays

Posted Liok

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;

 

以上是关于[LeetCode][Python]Intersection of Two Arrays的主要内容,如果未能解决你的问题,请参考以下文章

UVA12171-Sculpture(离散化+floodfill)

Leetcode.27 | Remove Element(Python)

LeetCode/Python: Reference Links

LeetCode 139. 单词拆分 | Python

LeetCode 0079. Word Search单词搜索Python

Leetcode.283 | Move Zeroes(Python)