55

LeetCode 第349题 Intersection of Two Arrays

 4 years ago
source link: https://www.tuicool.com/articles/rYFrYb7
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/

题目:两个数组的交集

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

Example 1:

<strong>Input: </strong>nums1 = [1,2,2,1], nums2 = [2,2]
<strong>Output: </strong>[2]

Example 2:

<strong>Input: </strong>nums1 = [4,9,5], nums2 = [9,4,9,8,4]
<strong>Output: </strong>[9,4]

Note:

  • 结果中每个元素都必须是不重复的。
  • 顺序不限。

这道题很简单,其实尤其是结果中元素要求不重复。那么我们简单的用hashmap实现就可以了。

首先用一个hashmap来统计第一个数组出现的数字。然后用第二hashmap统计第二个数组的数字,如果一个数字没有在第一个数组出现那么就也不把它加入第二个hashmap。最后第二个hashmap里面就包含了我们要的结果。(用hashset也一样做)

eAZFr2E.png!web

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

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK