2 回答
TA贡献1815条经验 获得超12个赞
如果您只需要判断是否存在重复值,而不需要知道哪些值是重复值或有多少个重复值,则用于跟踪现有值的最有效结构是具有空结构值的映射。
(为了方便起见,粘贴在下面):
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
}
TA贡献1946条经验 获得超3个赞
func main() {
m := map[int]int{
1: 100,
2: 200,
3: 100,
4: 400,
6: 200,
7: 700,
}
mNew := make(map[int]int)
for k, v := range m {
if val, has := mNew[v]; !has {
mNew[v] = k
} else {
fmt.Println(k, m[k], ",", val, m[val])
}
}
将映射键和值与新映射交换第二个映射不会插入重复键,因此您可以找到值
- 2 回答
- 0 关注
- 104 浏览
添加回答
举报