2 回答
TA贡献1842条经验 获得超12个赞
如果您的切片已排序,则可以完成这项工作。
package main
import "fmt"
// Subset return whether a is a sublist of b. Both a and b must be (weakly) ascending.
func Subset(a, b []int) bool {
for len(a) > 0 {
switch {
case len(b) == 0:
return false
case a[0] == b[0]:
a = a[1:]
b = b[1:]
case a[0] < b[0]:
return false
case a[0] > b[0]:
b = b[1:]
}
}
return true
}
func main() {
cases := []struct {
a, b []int
want bool
}{
{[]int{1, 2, 3}, []int{1, 2, 3, 4}, true},
{[]int{1, 2, 2}, []int{1, 2, 3, 4}, false},
}
for _, c := range cases {
if Subset(c.a, c.b) != c.want {
fmt.Printf("Subset(%v, %v) = %v, want %v\n", c.a, c.b, Subset(c.a, c.b), c.want)
}
}
}
- 2 回答
- 0 关注
- 315 浏览
添加回答
举报