Slice 取交集和差集的通用方法

2022-12-13
#go #code-snippet

交集

// GetIntersection intersection = a & b
func GetIntersection[T comparable](a []T, b []T) []T {
	set := make([]T, 0)
	hash := make(map[T]any)

	for _, v := range a {
		hash[v] = nil
	}

	for _, v := range b {
		if _, ok := hash[v]; ok {
			set = append(set, v)
		}
	}

	return set
}

差集

// GetSubtraction  subtraction = a - b
func GetSubtraction[T comparable](a []T, b []T) []T {
	set := make([]T, 0)
	hash := make(map[T]any)

	for _, v := range b {
		hash[v] = nil
	}

	for _, v := range a {
		if _, ok := hash[v]; !ok {
			set = append(set, v)
		}
	}

	return set
}