GO语言新手问题:两个切片如何去重

Chessman5210 · · 1599 次点击
func DelRepeat(first, second []int) (process []int) { firstMap := make(map[int]bool, len(first)) secondMap := make(map[int]bool, len(second)) for _, v := range first { firstMap[v] = false } for _, v := range second { secondMap[v] = false } for k, _ := range firstMap { if _, ok := secondMap[k]; ok { delete(secondMap, k) } process = append(process, k) } for k, _ := range secondMap { process = append(process, k) } return } ############## 测试用例 ########### func equalSlice(f,s []int) bool { if len(f) != len(s) { return false } fMap := make(map[int]struct{},len(f)) for _, v := range f { fMap[v] = struct{}{} } for _, v := range s { if _, ok := fMap[v]; !ok { return false } } return true } func TestDelRepeat(t *testing.T) { testCase := []struct{ Name string First []int Second []int Expect []int }{ { Name: "all null", First: []int{}, Second: []int{}, Expect: []int{}, }, { Name: "1", First: []int{1}, Second: []int{1}, Expect: []int{1}, }, { Name: "2", First: []int{1,1,1,1,1,1}, Second: []int{1}, Expect: []int{1}, }, { Name: "3", First: []int{1}, Second: []int{1,1,1,1,1,1}, Expect: []int{1}, }, { Name: "4", First: []int{1,2,3}, Second: []int{1,1,1,1,1,1}, Expect: []int{1,2,3}, }, { Name: "5", First: []int{1,1,1,1,1}, Second: []int{1,2,3}, Expect: []int{1,2,3}, }, { Name: "6", First: []int{1,1,1,1,1}, Second: []int{2,2,2,2}, Expect: []int{1,2}, }, { Name: "7", First: []int{1,1,1,2,3}, Second: []int{}, Expect: []int{1,2,3}, }, { Name: "8", First: []int{4,5,1,2,3}, Second: []int{5,6,6,6,7}, Expect: []int{1,2,3,4,5,6,7}, }, } for _, v := range testCase { t.Run(v.Name, func(t *testing.T) { n := DelRepeat(v.First, v.Second) if !equalSlice(n, v.Expect) { t.Fatalf("expect %++v now %++v\n", v.Expect, n) } }) } } ##### 可以发散一下, 把DelRepeat 弄成接口形式 可以支持任意的slice #####
#2
更多评论
- 利用map - 两个for分别遍历两个slice,把值存到map中 - 再赋值到新slice中
#1
哇...这样的排版也是醉了..
#3