doulan3966 2013-09-18 17:57
浏览 298
已采纳

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

I am looking for a efficient way to check if a slice is a subset of another. I could simply iterate over them to check, but I feel there has to be a better way.

E.g.

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

What is the best way to do this efficiently?

Thanks!

  • 写回答

2条回答 默认 最新

  • dongzhan5246 2013-09-18 18:47
    关注

    I think the most common way to solve a subset problem is via a 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}))
    }
    

    The ability to check duplicate values is relatively uncommon. The code above solves the problem as asked (see: http://play.golang.org/p/4_7Oh-fgDQ) though. If you plan on having duplicate values, you'll have to keep a count like the code above does. If there will not be duplicate values, you can solve the problem more compactly by using a boolean for the map value instead of an integer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭