登录
首页 >  Golang >  Go问答

确保在 Go 中的映射中没有重复值

来源:stackoverflow

时间:2024-03-14 12:12:25 377浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《确保在 Go 中的映射中没有重复值》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

考虑下面的地图

mymap := make(map[string]string)
mymap["a"] = "one"
mymap["b"] = "two"
mymap["c"] = "one"

如何确定值是否唯一?

一种策略是迭代地图,创建值的切片。然后迭代切片以查找重复项。有更好的办法吗?


解决方案


如果您只需要确定是否存在重复值,而不需要知道哪些值是重复值或有多少个重复值,则用于跟踪现有值的最有效结构是具有空结构值的映射。

参见 here(为方便起见,粘贴在下面):

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
}
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])
        }
    }

用新地图交换地图键和值 第二张地图不会插入重复的键,因此您可以找到值

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>