考虑以下地图
mymap := make(map[string]string)
mymap["a"] = "one"
mymap["b"] = "two"
mymap["c"] = "one"
Run Code Online (Sandbox Code Playgroud)
如何确定值是否唯一?
一种策略是遍历地图,创建值的切片。然后遍历切片以查找重复项。有没有更好的办法?
如果只需要对是否存在重复项进行判断,则无需知道哪些值是重复项或存在多少个重复项,那么用于跟踪现有值的最有效结构是具有空结构值的映射。
参见此处(为方便起见,粘贴在下面):
package main
import (
"fmt"
)
func hasDupes(m map[string]string) bool {
x := make(map[string]struct{})
for _, v := range m {
if _, has := x[v]; has {
return true
}
x[v] = struct{}{}
}
return false
}
func main() {
mapWithDupes := make(map[string]string)
mapWithDupes["a"] = "one"
mapWithDupes["b"] = "two"
mapWithDupes["c"] = "one"
fmt.Println(hasDupes(mapWithDupes)) // prints true
mapWithoutDupes := make(map[string]string)
mapWithoutDupes["a"] = "one"
mapWithoutDupes["b"] = "two"
mapWithoutDupes["c"] = "three"
fmt.Println(hasDupes(mapWithoutDupes)) // prints false
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
155 次 |
最近记录: |