go - 如何找到两个字符串 slice 之间的差异

标签 go

这是我想要的结果

slice1 := []string{"foo", "bar","hello"}
slice2 := []string{"foo", "bar"}

difference(slice1, slice2)
=> ["hello"]

我正在寻找两个字符串 slice 之间的区别!

最佳答案

假设 Go map 是 ~O(1),这是一个适用于未排序 slice 的 ~O(n) 差分函数。

// difference returns the elements in `a` that aren't in `b`.
func difference(a, b []string) []string {
    mb := make(map[string]struct{}, len(b))
    for _, x := range b {
        mb[x] = struct{}{}
    }
    var diff []string
    for _, x := range a {
        if _, found := mb[x]; !found {
            diff = append(diff, x)
        }
    }
    return diff
}

关于go - 如何找到两个字符串 slice 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19374219/

相关文章:

regex - 无法在正则表达式中捕获单引号

php - G-WAN,CGI 脚本的输出 header

go - 逃避反弹golang

golang 只从 json 获取一个统计信息

go - 如何使用RWMutex和升级锁

html - 使用 Go 的 net/html 分词器处理格式错误的 HTML?

google-app-engine - 没有路由器 Gorilla Mux 的 Google Cloud Go 处理程序?

戈朗 : Parse all templates in directory and subdirectories?

docker - docker compose up 后后端到 redis 连接被拒绝

go - Go中负整数的模