为了账号安全,请及时绑定邮箱和手机立即绑定

尝试在 Go 中实现 Java Guava sets.difference

尝试在 Go 中实现 Java Guava sets.difference

Qyouu 2021-10-17 10:42:02
Java番石榴Sets.difference行为:Known = ["v1","v2"]; Incoming = ["v2","v3","v4"]incoming = ["v2","v3","v4"]; knownUpdated = ["v2"]Sets.difference(Known, Incoming) = v1 (To be removed)Sets.difference(incoming, knownUpdated) = v3,v4 (To be added)我在 Go 中尝试过的有以下区别:Output := [v1 v3 v4] (known, Incoming) func Difference(slice1 []string, slice2 []string) []string {    var diff []string    for i := 0; i < 2; i++ {        for _, s1 := range slice1 {            found := false            for _, s2 := range slice2 {                if s1 == s2 {                    found = true                    break                }            }            if !found {                diff = append(diff, s1)            }        }        if i == 0 {            slice1, slice2 = slice2, slice1        }    }    return diff}它给出了对称的差异,但我需要 Guava sets.difference 的行为。我知道我的函数有问题。来自番石榴文档public static Sets.SetView difference(Set set1, Set set2):返回的集合包含由 set1 包含但由 set2 不包含的所有元素
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

最直接和易于理解的解决方案是使用映射 - 如果您只使用键,丢弃值,它们与许多其他集合实现(O(1)查找*,唯一键,无序)共享相似的属性。在这一点上,它实际上非常简单:


func Difference(slice1 []string, slice2 []string) []string {

    // Create proper "set" (Maps have unordered pairs and the keys are unique;

    // lookup to check whether value is present is O(1), similar to other

    // implementations)

    m := make(map[string]struct{}, len(slice1))

    for _, el := range slice1 {

        m[el] = struct{}{}

    }


    // Remove values from slice1 present in slice2

    for _, el := range slice2 {

        delete(m, el)

    }


    // Note that res will be non-deterministic: the order of iteration over maps

    // is made random on purpose by Go itself

    res := make([]string, 0, len(m))

    for k := range m {

        res = append(res, k)

    }

    return res

}


查看完整回答
反对 回复 2021-10-17
  • 1 回答
  • 0 关注
  • 206 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信