我如何估计两个循环的运行时间,每个循环以对数时间运行,如下所示:
In [60]: df.sort_values('Energy').groupby('spin').head(1)
Out[60]:
Energy spin
Particle 1 2 1
Particle 3 5 2
Particle 6 10 5
我的分析:
for(int i=n; i>=0; i /= 2)
{
for( int j=i; j>=0; j /= 2)
{
count++;
}
}
如何总结这种情况下的对数项?
答案 0 :(得分:4)
i = n. | Inner loop runs log(n) iterations. | O(log(n))
i = n/2. | Inner loop runs log(n/2) iterations. | O(log(n))
i = n/4. | Inner loop runs log(n/4) iterations. | O(log(n))
. | |
. | |
i = log(n). | Inner loop runs log(log(n)) iterations. | O(log(log(n)))
我们注意到了什么?对于每个n
,我们正在添加O(log(n))
此重现是T(n) = T(n/2) + log(n) + 1
可以通过以下方式扩展:
T(n) = log(n) + log(n/2) + log(n/4) + ... + 1
= log(n) + [log(n)-1] + [log(n)-2] + [log(n) - 3] + .... + 1
= log(n)*log(n) - (2 + 3 + .... log(n))
= log(n)*log(n) - ([(2+log(n))*log(n)]/2)
= log(n)*log(n) - ~0.5log(n)*log(n)
= ~0.5log(n)*log(n)
T(n) = O(log(n)*log(n))