[LeetCode][Python]Intersection of Two Arrays II

Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to num2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

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;
原文地址:https://www.cnblogs.com/Liok3187/p/5517848.html