题目
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
- Each element in the result must be unique.
- The result can be in any order.
解题思路
- 将nums1中的元素放入map[int]bool中,值初始化为false
- 遍历nums2,map中存在的元素值置为true
- 遍历map,取出值为true的元素
注意
第三步遍历map的目的是防止有多个重复的相交元素出现
代码
intersection.go
package _349_Intersection_of_Two_Arrays
func intersection(nums1 []int, nums2 []int) []int {
var ret []int
var numMap map[int]bool
numMap = make(map[int]bool)
for _, v := range nums1 {
numMap[v] = false
}
for _, v := range nums2 {
_, ok := numMap[v]
if ok {
numMap[v] = true
}
}
for k, v := range numMap {
if v {
ret = append(ret, k)
}
}
return ret
}