3

LeetCode 第350题 Intersection of Two Arrays II

 3 years ago
source link: https://codechina.org/2019/08/leetcode-350-intersection-of-two-arrays-ii/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

来源:https://leetcode.com/problems/intersection-of-two-arrays-ii/

题目:两个数组的交集II

给定两个数组,计算他们的交集。

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • 每个元素在结果中出现的次数,由他们在两个数组中同时出现的次数决定。
  • 结果集顺序无关。

这道题基本思路跟第349题 Intersection of Two Arrays没有本质区别,但是稍微麻烦一点,需要统计元素出现的次数了。

首先我们用两个hashmap分别统计两个数组的元素以及他们出现的次数。然后,我们把两个hashmap的keyset和成一个新的keyset。

1-1.png

然后我们遍历这个新的keyset,然后找到这两个hashmap中这些数值的最小值,如果不包含这个数值就自然为0。然后根据这个最小值在结果集中加入相应数量的数字。

2-1-1024x455.png

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0350

本题属于哈希表类题目,想了解更多关于哈希表的题目,可以参看哈希表专题

发表评论 取消回复

邮箱地址不会被公开。 必填项已用*标注

评论

姓名 *

电子邮件 *

站点

在此浏览器中保存我的姓名、电子邮件和站点地址。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK