切片交集,并集和差集

交集,并集和差集算法

Posted by 果果 on November 23, 2022

golang得到切片的交集,并集和差集

package main

import "fmt"

func intersect(s1, s2 []int) []int {
	var ret []int
	m := make(map[int]int)
	for _, v := range s1 {
		m[v]++
	}

	for _, v := range s2 {
		vv := m[v]
		if vv > 0 {
			ret = append(ret, v)
		}
	}
	return ret
}

func union(s1, s2 []int) []int {
	m := make(map[int]int)
	for _, v := range s1 {
		m[v]++
	}

	for _, v := range s2 {
		vv := m[v]
		if vv == 0 {
			s1 = append(s1, v)
		}
	}
	return s1
}

func diff(s1, s2 []int) []int {
	var ret []int
	s3 := intersect(s1, s2)
	m := make(map[int]int)
	for _, v := range s3 {
		m[v]++
	}

	for _, v := range s1 {
		vv := m[v]
		if vv == 0 {
			ret = append(ret, v)
		}
	}

	for _, v := range s2 {
		vv := m[v]
		if vv == 0 {
			ret = append(ret, v)
		}
	}
	return ret
}

func main() {
	s1 := []int{1, 3, 4, 6}
	s2 := []int{1, 2, 5, 6}
	
	s3 := intersect(s1, s2)
	s4 := union(s1, s2)
	s5 := diff(s1, s2)

	fmt.Println("slice1与slice2的并集为:", s4)
	fmt.Println("slice1与slice2的交集为:", s3)
	fmt.Println("slice1与slice2的差集为:", s5)
}