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中的,所以都添加进去了,所以导致的结果不对。
代码:
解法一:
解法二:
解法三(不可行,仅供理解):
- Leetcode之Intersection of Two Arrays II 问题
- leetcode之Intersection of Two Arrays II
- Leetcode 之 Intersection of Two Arrays II
- Leetcode之Intersection of Two Arrays 问题
- LeetCode之路:350. Intersection of Two Arrays II
- [LeetCode] Intersection of Two Arrays II
- LeetCode Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- LeetCode:Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- LeetCode 350:Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- leetcode Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [python][leetcode]Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- 【转载】Java中Properties类操作
- nrf51蓝牙未连接超时自动关机
- R中文分词、绘制云图笔记
- 定时器
- Python3 元组
- Leetcode之Intersection of Two Arrays II 问题
- Tomcat(一) Tomcat是什么:Tomcat与Java技术 Tomcat与Web应用 以及 Tomcat基本框架及相关配置
- 56.Scala中Self Types实战详解
- java序列化和反序列化
- 九月英语
- 2.java线程-thread vs runnable
- 覆盖虚表方式利用栈溢出漏洞
- Java语言基础组成(上)
- cadence 16.6 allegro PCB Editor快捷键调整格点大小