思路:
1、通过append把两数组合并成一个数组
arr = append(arr,arr1...)
2、通过map的特性将数组中重复的元素找出来
sameElem := make(map[int]int) //定义一个空map
_, ok := sameElem[v] //利用ok表达式,往map中插入数组的元素,如果map中已经存在,则ok为true,反之为false
完整代码
package main
import "fmt"
func ArrayIntersection(arr []int, arr1 []int) []int {
var intersection []int
arr = append(arr, arr1...)
sameElem := make(map[int]int)
for _, v := range arr {
if _, ok := sameElem[v]; ok {
intersection = append(intersection, v)
} else {
sameElem[v] = 1
}
}
return intersection
}
func main() {
arr1 := []int{1, 2, 3, 4, 5, 6}
arr2 := []int{5, 6, 7, 8, 9, 0}
fmt.Println(ArrayIntersection(arr1, arr2))
}
输出结果:
[5,6]
有疑问加站长微信联系(非本文作者)