Files
leetcode/data-structure/ds-set_test.go
T
2026-07-20 19:57:25 +08:00

91 lines
1.7 KiB
Go

package ds
import (
"reflect"
"sort"
"testing"
)
func TestSetBasic(t *testing.T) {
s := NewSet[int]()
if !s.Empty() {
t.Fatal("新建应为空")
}
s.Add(1)
s.Add(2)
s.Add(1) // 重复
if s.Len() != 2 {
t.Fatalf("Len = %d, want 2", s.Len())
}
if !s.Contains(1) {
t.Fatal("应包含 1")
}
if s.Contains(3) {
t.Fatal("不应包含 3")
}
s.Remove(1)
if s.Contains(1) {
t.Fatal("Remove 后不应再包含 1")
}
}
func TestSetFromSlice(t *testing.T) {
s := NewSetFrom([]string{"a", "b", "a", "c", "b"})
if s.Len() != 3 {
t.Fatalf("Len = %d, want 3", s.Len())
}
for _, want := range []string{"a", "b", "c"} {
if !s.Contains(want) {
t.Fatalf("应包含 %q", want)
}
}
}
func TestSetUnionIntersectDiff(t *testing.T) {
a := NewSetFrom([]int{1, 2, 3, 4})
b := NewSetFrom([]int{3, 4, 5, 6})
u := a.Union(b)
if !sameSet(u, NewSetFrom([]int{1, 2, 3, 4, 5, 6})) {
t.Fatalf("Union = %v, want {1,2,3,4,5,6}", sortedSlice(u))
}
i := a.Intersect(b)
if !sameSet(i, NewSetFrom([]int{3, 4})) {
t.Fatalf("Intersect = %v, want {3,4}", sortedSlice(i))
}
d := a.Difference(b)
if !sameSet(d, NewSetFrom([]int{1, 2})) {
t.Fatalf("Difference = %v, want {1,2}", sortedSlice(d))
}
}
func TestSetToSlice(t *testing.T) {
s := NewSetFrom([]int{3, 1, 2})
got := sortedSlice(s)
want := []int{1, 2, 3}
if !reflect.DeepEqual(got, want) {
t.Fatalf("ToSlice(sorted) = %v, want %v", got, want)
}
}
// sameSet 比较两个集合元素是否相同(忽略顺序)。
func sameSet[T comparable](a, b *Set[T]) bool {
if a.Len() != b.Len() {
return false
}
for v := range a.m {
if _, ok := b.m[v]; !ok {
return false
}
}
return true
}
func sortedSlice(s *Set[int]) []int {
out := s.ToSlice()
sort.Ints(out)
return out
}