arrays - 在 Go 中使用 slice 进行子集检查

标签 arrays go subset slice

我正在寻找一种有效的方法来检查 slice 是否是另一个 slice 的子集。我可以简单地遍历它们来检查,但我觉得必须有更好的方法。

例如

{1, 2, 3} is a subset of {1, 2, 3, 4}
{1, 2, 2} is NOT a subset of {1, 2, 3, 4}

有效执行此操作的最佳方法是什么?

谢谢!

最佳答案

我认为解决子集问题最常见的方法是通过 map 。

package main

import "fmt"

// subset returns true if the first array is completely
// contained in the second array. There must be at least
// the same number of duplicate values in second as there
// are in first.
func subset(first, second []int) bool {
    set := make(map[int]int)
    for _, value := range second {
        set[value] += 1
    }

    for _, value := range first {
        if count, found := set[value]; !found {
            return false
        } else if count < 1 {
            return false
        } else {
            set[value] = count - 1
        }
    }

    return true
}

func main() {
    fmt.Println(subset([]int{1, 2, 3}, []int{1, 2, 3, 4}))
    fmt.Println(subset([]int{1, 2, 2}, []int{1, 2, 3, 4}))
}

检查重复值的能力相对不常见。上面的代码解决了问题(参见:http://play.golang.org/p/4_7Oh-fgDQ)。如果您计划使用重复值,则必须像上面的代码一样进行计数。如果不存在重复值,您可以通过对映射值使用 bool 值而不是整数来更紧凑地解决问题。

关于arrays - 在 Go 中使用 slice 进行子集检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57803867/

相关文章:

arrays - 如何在 Angular 2 中使用 TypeScript 过滤数组?

json - golang中存储日期时间偏移量的数据类型

r - 基于字符向量进行子集化时,knit_expand 失败

python - 反转数组的比例

c++ - 优化:为什么 < 比 multiple 更昂贵!=

c - Qsort 数组 |警告 : initialization discards qualifiers from pointer target type

ssl - 如何在原生 Go 中将 PEM 证书链转换为 PKCS7?

go - 我可以使用 autocert 的动态主机策略吗?

r - 如何获得选择的项目数?

r - 如何从R中的另一个向量中减去具有重复字符的完整字符向量