[LeetCode] 350. Intersection of Two Arrays II #350
Comments
follow up questions not answered |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
follow up questions not answered |
Given two arrays, write a function to compute their intersection.
Example 1:
Example 2:
Note:
Follow up:
这道题是之前那道 Intersection of Two Arrays 的拓展,不同之处在于这道题允许返回重复的数字,而且是尽可能多的返回,之前那道题是说有重复的数字只返回一个就行。那么这道题用 HashMap 来建立 nums1 中字符和其出现个数之间的映射, 然后遍历 nums2 数组,如果当前字符在 HashMap 中的个数大于0,则将此字符加入结果 res 中,然后 HashMap 的对应值自减1,参见代码如下:
解法一:
再来看一种方法,这种方法先给两个数组排序,然后用两个指针分别指向两个数组的起始位置,如果两个指针指的数字相等,则存入结果中,两个指针均自增1,如果第一个指针指的数字大,则第二个指针自增1,反之亦然,参见代码如下:
解法二:
Github 同步地址:
#350
类似题目:
Intersection of Two Arrays
Find Common Characters
参考资料:
https://leetcode.com/problems/intersection-of-two-arrays-ii/
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82269/Short-Python-C%2B%2B
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82241/AC-solution-using-Java-HashMap
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82263/C%2B%2B-hash-table-solution-and-sort-%2B-two-pointers-solution-with-time-and-space-complexity
LeetCode All in One 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered: