栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Go中使用切片进行子集检查

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Go中使用切片进行子集检查

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

package mainimport "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)。如果您打算使用重复的值,则必须像上面的代码一样保留一个计数。如果没有重复的值,则可以通过使用布尔值(而不是整数)来更紧凑地解决问题。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/436228.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号