Golang找两个切片的交差集
func difference(slice1, slice2 []int) []int { //取要校验的和已经校验过的差集,找出需要校验的切片IP(找出slice1中 slice2中没有的) m := make(map[int]int) n := make([]int,0) inter := intersect(slice1, slice2) for _, v := range inter { m[v]++ } for _, value := range slice1 { if m[value] == 0 { n = append(n, value) } } for _, v := range slice2 { if m[v] == 0 { n = append(n, v) } } return n } func intersect(slice1, slice2 []int) []int { // 取两个切片的交集 m := make(map[int]int) n := make([]int, 0) for _, v := range slice1 { m[v]++ } for _, v := range slice2 { times, _ := m[v] if times == 1 { n = append(n, v) } } return n }
摘自:https://blog.csdn.net/weixin_43202081/article/details/108050870
第二种:
//第二种
func getDifference( slice1, slice2 []int) []int { var diff []int for _,val:= range slice1{ if bool := Contain(val, slice2); bool == false{ diff = append(diff,val) } } return diff } func Contain(obj interface{}, target interface{}) (bool) { targetValue := reflect.ValueOf(target) switch reflect.TypeOf(target).Kind() { case reflect.Slice, reflect.Array: for i := 0; i < targetValue.Len(); i++ { fmt.Println("****",targetValue.Index(i)) if targetValue.Index(i).Interface() == obj { return true } } } return false }
第三种:
package php //ArrayDiff 模拟PHP array_diff函数 func ArrayDiff(array1 []interface{}, othersParams ...[]interface{}) ([]interface{}, error) { if len(array1) == 0 { return []interface{}{}, nil } if len(array1) > 0 && len(othersParams) == 0 { return array1, nil } var tmp = make(map[interface{}]int, len(array1)) for _, v := range array1 { tmp[v] = 1 } for _, param := range othersParams { for _, arg := range param { if tmp[arg] != 0 { tmp[arg]++ } } } var res = make([]interface{}, 0, len(tmp)) for k, v := range tmp { if v == 1 { res = append(res, k) } } return res, nil } //ArrayIntersect 模拟PHP array_intersect函数 func ArrayIntersect(array1 []interface{}, othersParams ...[]interface{}) ([]interface{}, error) { if len(array1) == 0 { return []interface{}{}, nil } if len(array1) > 0 && len(othersParams) == 0 { return array1, nil } var tmp = make(map[interface{}]int, len(array1)) for _, v := range array1 { tmp[v] = 1 } for _, param := range othersParams { for _, arg := range param { if tmp[arg] != 0 { tmp[arg]++ } } } var res = make([]interface{}, 0, len(tmp)) for k, v := range tmp { if v > 1 { res = append(res, k) } } return res, nil } //demo var sl2 = []interface{}{7, 8, 9, 10, "ff"} var sl3 = []interface{}{"sds", "dddd", "ff", "yy"} res, err := php.ArrayIntersect(sl2, sl3) if err == nil { fmt.Println(res) } else { fmt.Println(err) }