dpi74187 2015-06-26 06:06
浏览 26
已采纳

如何检查地图是否可以在Golang中部分匹配其他地图

Suppose, I have two map[string]([]string)

 MAP1 := map[string]([]string) {
    "User" : []string{"11", "33"},
    "Type" : []string{"A"},
    }


MAP2 := map[string]([]string) {
    "User" : []string{"11", "17"},
    "Type" : []string{"B"},
    }

Here, MAP1 matches MAP2 partially.

User = 11 is in both map

How can I check this in a easy way?

  • 写回答

2条回答 默认 最新

  • doupingzhi9674 2015-06-26 09:28
    关注

    For example:

    package main
    
    import "fmt"
    
    func Max(x, y int) int {
        if x > y {
            return x
        }
        return y
    }
    
    func Intersect(as, bs []string) []string {
        i := make([]string, 0, Max(len(as), len(bs)))
        for _, a := range as {
            for _, b := range bs {
                if a == b {
                    i = append(i, a)
                }
            }
        }
        return i
    }
    
    func main() {
    
        MAP1 := map[string][]string{
            "User": []string{"11", "33"},
            "Type": []string{"A"},
        }
    
        MAP2 := map[string][]string{
            "User": []string{"11", "17"},
            "Type": []string{"B"},
        }
    
        MAP3 := make(map[string][]string)
    
        for k, _ := range MAP1 {
            MAP3[k] = Intersect(MAP1[k], MAP2[k])
        }
    
        fmt.Println(MAP3) // MAP3 contains commonalities between MAP1 and MAP2
    }
    

    Note that this solution does not exploit any potential performance optimizations (like assuming that the string arrays will be sorted in some way, or else) and hence has a runtime performance of O(m • n2), where:

    • m is the number of keys in the map (assumed to be the same for both maps)
    • n is the number of elements in each string slice (assumed to be the same for both corresponding map entries)

    Which is okay but not great.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题