猿问

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

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 不包含的所有元素


Qyouu
浏览 207回答 1
1回答

天涯尽头无女友

最直接和易于理解的解决方案是使用映射 - 如果您只使用键,丢弃值,它们与许多其他集合实现(O(1)查找*,唯一键,无序)共享相似的属性。在这一点上,它实际上非常简单:func Difference(slice1 []string, slice2 []string) []string {&nbsp; &nbsp; // Create proper "set" (Maps have unordered pairs and the keys are unique;&nbsp; &nbsp; // lookup to check whether value is present is O(1), similar to other&nbsp; &nbsp; // implementations)&nbsp; &nbsp; m := make(map[string]struct{}, len(slice1))&nbsp; &nbsp; for _, el := range slice1 {&nbsp; &nbsp; &nbsp; &nbsp; m[el] = struct{}{}&nbsp; &nbsp; }&nbsp; &nbsp; // Remove values from slice1 present in slice2&nbsp; &nbsp; for _, el := range slice2 {&nbsp; &nbsp; &nbsp; &nbsp; delete(m, el)&nbsp; &nbsp; }&nbsp; &nbsp; // Note that res will be non-deterministic: the order of iteration over maps&nbsp; &nbsp; // is made random on purpose by Go itself&nbsp; &nbsp; res := make([]string, 0, len(m))&nbsp; &nbsp; for k := range m {&nbsp; &nbsp; &nbsp; &nbsp; res = append(res, k)&nbsp; &nbsp; }&nbsp; &nbsp; return res}
随时随地看视频慕课网APP

相关分类

Java
我要回答