简体   繁体   English

算法的时间复杂度 - n或n * n?

[英]Time complexity of an algorithm - n or n*n?

I'm trying to find out which is the Theta complexity of this algorithm. 我试图找出这个算法的Theta复杂性。 (a is a list of integers) (a是整数列表)

def sttr(a):
    for i in xrange(0,len(a)):
        while s!=[] and a[i]>=a[s[-1]]:
            s.pop()
        s.append(i)
    return s

On the one hand, I can say that append is being executed n (length of a array) times, so pop too and the last thing I should consider is the while condition which could be executed probably 2n times at most. 一方面,我可以说append正在执行n (数组的长度)次,所以pop也是最后一件事我应该考虑的是while条件,最多可能执行2n次。

From this I can say that this algorithm is at most 4*n so it is THETA(n). 由此我可以说这个算法最多是4*n所以它是THETA(n)。

But isn't it amortised analysis? 但是不是摊销分析吗?

On the other hand I can say this: 另一方面,我可以这样说:

There are 2 nested cycles. 有2个嵌套循环。 The for cycle is being executed exactly n times. for循环正好执行n次。 The while cycle could be executed at most n times since I have to remove item in each iteration. 由于我必须在每次迭代中删除项目,因此while循环最多n次。 So the complexity is THETA(n*n). 所以复杂性是THETA(n * n)。

I want to compute THETA but don't know which of these two options is correct. 我想计算THETA,但不知道这两个选项中哪一个是正确的。 Could you give me advice? 你能给我一些建议吗?

The answer is THETA(n) and your arguments are correct. 答案是THETA(n) ,你的论点是正确的。

This is not amortized analysis. 这不是摊销分析。

To get to amortized analysis you have to look at the inner loop. 要进行摊销分析,您必须查看内循环。 You can't easily say how fast the while will execute if you ignore the rest of the algorithm. 如果忽略算法的其余部分,你不能轻易地说出执行的速度有多快。 Naive approach would be O(N) and that's correct since that's the maximum number of iterations. 朴素的方法是O(N),这是正确的,因为这是最大的迭代次数。 However, since we know that the total number of executions is O(N) (your argument) and that this will be executed N time we can say that the complexity of the inner loop is O(1) amortized. 但是,因为我们知道执行的总数是O(N)(你的参数)并且这将被执行N次,我们可以说内循环的复杂性是O(1)摊销的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM