码迷,mamicode.com
首页 > 编程语言 > 详细

三路集合不相交(Three-Way Set Disjointness)算法分析

时间:2018-06-20 00:51:27      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:disjoint   原理   概念   The   code   相交   for   长度   复杂   

概念介绍

实际上,无论是三路,还是多路,原理是类似的。三路集合不相交,指存在3个由一系列数字组成的集合,在任意集合中,不存在相同的元素。且同时满足:对于任意的x,不存在x $ \in $ A,x $ \in $ B,且x $ \in $ C。

实现一

def disjoint1(A, B, C):
    """Return True if there is no element common to all three lists"""
    for a in A:
        for b in B:
            for c in C:
                if a == b == c:
                    return False   # we found a common vale
    return True                    # if we reach this, sets are disjoint

很显然,三层嵌套,对于集合长度都为n的A,B,C来说,总的时间复杂度为O($ n^3 $)。

实现二

def disjoint2(A, B, C):
    """Return True if there is no element common to all three lists"""
    for a in A:
        for b in B:
            if a == b:                    # only check C if we found match from A and B
                for c in C:
                    if a == C:            # (and thus a == b == c)
                        return False      # we found a common value
    return True                           # if we reach this, sets are disjoint

为了计算总的时间复杂度,需要逐层分析。

  • 首先,外层循环A为O(n),内层循环B为O($ n^2 $)。

  • 对于if a== b来说,总共会执行O($ n^2 $)次判断。

  • 剩下的时间取决于(a, b)相等的次数。由于集合的互异性,那么a和b相等的次数为n。因为一旦a == b成立,则a不等于在B中除b以外的元素。

  • 由于a == b的次数为n,则对于最内层循环及其循环体,其时间复杂度为O($ n^2 $)。

综上,总的时间复杂度仍为O($ n^2 $)。

总结

通过不同的算法时间,可以减少程序执行的时间复杂度,进而对程序进行优化以提高效率。

三路集合不相交(Three-Way Set Disjointness)算法分析

标签:disjoint   原理   概念   The   code   相交   for   长度   复杂   

原文地址:https://www.cnblogs.com/jeffrey-yang/p/9140649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!