方法一 双重for循环,设置标识,增加到新的切片中,达到去重效果:
func main() {
var arr = []string{"hello", "hi", "world", "hi", "china", "hello", "hi"}
fmt.Println(RemoveRepeatedElement(arr))
}
func RemoveRepeatedElement(arr []string) (newArr []string) {
newArr = make([]string, 0)
for i := 0; i < len(arr); i++ {
repeat := false
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] {
repeat = true
break
}
}
if !repeat {
newArr = append(newArr, arr[i])
}
}
return
}
方法二: 通过map键的唯一性去重
//第二种写法:更简洁点
func RemoveRepeated(s []int) []int {
start := time.Now()
result := []int{}
m := make(map[int]bool) //map的值不重要
for _, v := range s {
if _, ok := m[v]; !ok {
result = append(result, v)
m[v] = true
}
}
fmt.Println("花费时间:", fmt.Sprintf("%vms", (time.Now().UnixNano()-start.UnixNano())/1e+6))
return result
}
//第二种写法:
var strMap make(map[string]string)
strSlice := []string {"slice","int","string","int","boolean","string"}
for _,v:= range strSlice{
strMap[v] = v
}
//strMap为:{"slice":"slice","int":"int","string":"string","boolean":boolean"}
//如果想将map转换为slice,可利用数组的append函数
var secondStr []string
for _,value := range strMap{
secondStr = append(secondStr ,value)
}
//secondStr为:{"slice","int","string","boolean"}
方法三:利用反射和interface实现, 我有点看不懂
func main() {
b := []string{"a", "b", "c", "c", "e", "f", "a", "g", "b", "b", "c"}
sort.Strings(b)
fmt.Println(Duplicate(b))
c := []int{1, 1, 2, 4, 6, 7, 8, 4, 3, 2, 5, 6, 6, 8}
sort.Ints(c)
fmt.Println(Duplicate(c))
}
func Duplicate(a interface{}) (ret []interface{}) {
va := reflect.ValueOf(a)
for i := 0; i < va.Len(); i++ {
if i > 0 && reflect.DeepEqual(va.Index(i-1).Interface(), va.Index(i).Interface()) {
continue
}
ret = append(ret, va.Index(i).Interface())
}
return ret
}