[LeetCode][Python]Intersection of Two Arrays II

Posted Liok

tags:

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

 

 

 

 

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

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)