LeetCode 349. 两个数组的交集
题目描述
思路分析
- 哈希表
- 排序+双指针
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func intersection(nums1 []int, nums2 []int) []int {
set1 := make(map[int]struct{})
res := []int{}
// 将 nums1 的元素加入 set1
for _, num := range nums1 {
set1[num] = struct{}{}
}
// 遍历 nums2,查找交集
for _, num := range nums2 {
if _, exists := set1[num]; exists {
res = append(res, num)
delete(set1, num) // 删除已添加的元素,确保不重复
}
}
return res
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用