[]sting去重?

cxyqiangge668 · · 995 次点击
声明一个 map[string]int ,循环遍历 []string 并将 string 依次写到 map 中,最终的到的 map 的 key 组成的数组就是去重了的
#2
更多评论
func Remove(a []string) (ret []string) { a_len := len(a) for i := 0; i < a_len; i++ { if (i > 0 && a[i-1] == a[i]) || len(a[i]) == 0 { continue } ret = append(ret, a[i]) } return } 详细:https://studygolang.com/articles/6584
#1
buscoop
纸上得来终觉浅,绝知此事要躬行!
``` package main import "fmt" func removeDuplicates(elements []string) []string { encountered := map[string]bool{} result := []string{} for _,v := range elements { if _,ok := encountered[v] ;!ok { encountered[v] = true result = append(result, v) } } return result } func main() { elements := []string{"a", "bc", "bc", "ddd", "eef", "ddd", "baw"} fmt.Println(elements) result := removeDuplicates(elements) fmt.Println(result) } ```
#3