orgSlice := []int{1,2,3}newSlice := []int{}newInt := 2newSlice = append(newSlice,newInt)for _,v := range orgSlice if v != newInt newSlice = append(newSlice,v) newSlice == code] : r1 w5 A; P# _1 s
解决方案: 6 a1 l1 C+ R' _' H/ b8 @: u
每次插入方法都需要线性时间。更好的方法是使用它map[int]struct{}.或者,你也可以使用 amap[int]bool或者类似的东西,但是空的struct{}的优点是它不占用任何额外的空间。map[int]struct{}是一组整数的流行选择。/ T% {" i! {& H& v+ F# k
例子:[code]set := make(map[int]struct{})set[1] = struct{}{}set[2] = struct{}{}set[1] = struct{}{}/ ...for key := range(set) { fmt.Println(key)}// each value will be printed only once,in no particular order// you can use the ,ok idiom to check for existing keysif _,ok := set[1]; ok { fmt.Println("element found")} else { fmt.Println("element not found")}% ]7 i, _6 W0 Y