Leetcode之Intersection of Two Arrays II 问题

来源:互联网 发布:网络少年图片 编辑:程序博客网 时间:2024/06/05 15:08

问题描述:

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

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 nums2'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?

示例:

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

题目来源:Intersection of Two Arrays II (详细地址:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/)

思路分析:这道题和Intersection of Two Arrays 的意思是差不多的,只是在输出结果上有点不同而已,Intersection of Two Arrays 只需要输出一次重复数字而已,而在这我们需要重复输出,有几次我们就输出几次。所以在这我们不能用set了,那我们就把set换成list试试。

解法一:两个指针+list,你会发现是可行的,在这我不多说了,具体咋操作的咱看代码吧;

解法二:我们可以使用hashmap来试试,key用来存储数组元素,value用来存储该元素出现的次数。用这种方式将其中一个数组存储好,我们接着遍历第二个数组,如果map中含有这个元素且它出现了不止一次(大于或等于一次),我们就将它存放到结果中,并且这个数出现的次数应该减一次了。等到下一次再次遍历到这个数的时候,如果它出现的次数还是大于1的话,我们就再添加一次,最后用数组的形式返回就行了;

解法三:两个list,你会发现这种办法是不可行的(结合Intersection of Two Arrays 中的代码看),举个特例:nums1:[1],nums2:[1, 1],在这输出了[1, 1],但是真是结果应该是[1]。为什么会出现这种情况呢?我们添加完数组1之后,其中一个list就只有1这个元素,然后我们遍历第二个数组的时候,发现数组中的两个元素都匹配,都是存在于list中的,所以都添加进去了,所以导致的结果不对。

代码:

解法一:


解法二:

解法三(不可行,仅供理解):