【发布时间】:2016-10-16 04:19:15
【问题描述】:
O(n) 因为将list转换为set是O(n)时间,得到交集是O(n)时间,len是O(n)
def disjoint3c(A, B, C):
"""Return True if there is no element common to all three lists."""
return len(set(A) & set(B) & set(C)) == 0
或者类似的,显然应该是O(N)
def set_disjoint_medium (a, b, c):
a, b, c = set(a), set(b), set(c)
for elem in a:
if elem in b and elem in c:
return False
return True
但是这个 O(n^3) 代码:
def set_disjoint_slowest (a, b, c):
for e1 in a:
for e2 in b:
for e3 in c:
if e1 == e2 == e3:
return False
return True
跑得更快
查看算法一是 n^3 的时间,算法三是 O(n) 集合代码...算法二实际上是 n^2,我们通过在第三个循环开始之前检查不相交来优化算法一
Size Input (n): 10000
Algorithm One: 0.014993906021118164
Algorithm Two: 0.013481855392456055
Algorithm Three: 0.01955580711364746
Size Input (n): 100000
Algorithm One: 0.15916991233825684
Algorithm Two: 0.1279449462890625
Algorithm Three: 0.18677806854248047
Size Input (n): 1000000
Algorithm One: 1.581618070602417
Algorithm Two: 1.146049976348877
Algorithm Three: 1.8179030418395996
【问题讨论】:
-
您需要说明一下您用于测试的输入。在这些算法中,时间可能会非常不同,具体取决于输入共有多少个元素。顺便说一句,Python 中的
len(set)是O(1)。 -
O(n) 只保证在大 n 的限制下比 O(n^3) 快。例如 4000*n+log(n) 是 O(n) 但比 2*n^3 更大(或更慢),因为 n=5 是 O(n^3)。
-
请注意,Big-Oh 符号并不总是决定性能。在 Python 中,迭代列表非常快,set/dict 查找稍慢(作为哈希表)。然后你有将列表转换为集合的开销。
标签: python algorithm complexity-theory