Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
Follow up:
https://leetcode.com/problems/intersection-of-two-arrays-ii/
把一个数组中的元素的元素对应到哈希表,key是值,value是出现的次数,然后对照哈希表遍历另一个数组,O(n)。
follow up的问题:
1. 两个数组都有序的话可以用双指针;
2. 把num1做成哈希表,数量比较少;
3. 也是把num1做成哈希表,nums2比较多就读一点处理一点。
1 class Solution(object): 2 def intersect(self, nums1, nums2): 3 """ 4 :type nums1: List[int] 5 :type nums2: List[int] 6 :rtype: List[int] 7 """ 8 res = []; dictionary = {} 9 for num in nums1: 10 if not dictionary.has_key(num): 11 dictionary[num] = 1 12 else: 13 dictionary[num] += 1 14 for num in nums2: 15 if dictionary.has_key(num) and dictionary[num] > 0: 16 dictionary[num] -= 1 17 res.append(num) 18 return res;
[LeetCode][Python]Intersection of Two Arrays II
原文:http://www.cnblogs.com/Liok3187/p/5517848.html