Leetcode 0349. Intersection of Two Arrays
349. Intersection of Two Arrays
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
1 | Input: nums1 = [1,2,2,1], nums2 = [2,2] |
Example 2:
1 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] |
题目大意
给定两个整数数组 nums1 和 nums2,返回它们的交集。结果中的每个元素必须是唯一的,并且可以按任意顺序返回。
解题思路
可以使用哈希集合来高效求解:
- 先将第一个数组中的元素存入一个哈希集合,自动去除重复元素
- 遍历第二个数组,检查每个元素是否存在于第一个数组的哈希集合中
- 若存在,将其加入结果集合(自动去重)
- 最后将结果集合转换为数组返回
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

