标签:
ints := []int{9, 1, 9, 4, 5, 5, 2, 3, 3, 2}
从最简单的int切片开始,自己第一次想到的函数代码如下:
func UniqueInts(ints []int) []int {
ms := map[int]int{}
for _, i := range ints {
ms[i] = i
}
var result []int
for _, s := range ms {
result = append(result, s)
}
return result
}
算不上高明,胜在简单易读,之后找了下书上的源码,其代码如下:
func UniqueInts(slice []int) []int {
seen := map[int]bool{} // == make(map[int]bool)
unique := []int{} // == make([]int, 0)
for _, x := range slice {
//查找map中的元素,如果不是重复的int则添加到map中
if _, found := seen[x]; !found {
//把元素添加到新的切片中,利用了map的特性,保证了不重复
unique = append(unique, x)
seen[x] = true
}
}
return unique
}
标签:
原文地址:http://www.cnblogs.com/qzyuanmu/p/4326471.html