Browse Source

添加两个slice求差集的函数

yjp 4 months ago
parent
commit
23e95de952
1 changed files with 21 additions and 0 deletions
  1. 21 0
      slice/slice.go

+ 21 - 0
slice/slice.go

@@ -72,3 +72,24 @@ func ExtractUnionValue[T comparable](aList, bList []T) []T {
 	cList = RemoveRepeatElement(cList)
 	return cList
 }
+
+func ExtractASubBSetValue[T comparable](aList, bList []T) []T {
+	aList = RemoveRepeatElement(aList)
+	bList = RemoveRepeatElement(bList)
+	cList := make([]T, 0)
+
+	// 使用 map 标记 bList 中的元素
+	tmpMap := make(map[T]struct{})
+	for _, item := range bList {
+		tmpMap[item] = struct{}{}
+	}
+
+	// 遍历 aList,将不在 bList 中的元素加入cList
+	for _, item := range aList {
+		if _, ok := tmpMap[item]; !ok {
+			cList = append(cList, item)
+		}
+	}
+
+	return cList
+}