我正在寻找一种有效的方法来检查 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/