伪代码的时间复杂度

时间:2018-03-09 11:50:22

标签: time time-complexity

我有一个算法,我试图找到时间复杂度。

 (A[1...n]: array of integers) 
    stack S ← empty stack 
    for k ← 1 to n         
        push(S, A[k])        
        x ← 4   
        while (S is not empty) and (x is even)     
             x ← pop(S)  

我认为while循环每次迭代只迭代一次,导致O(n)。这是对的吗?

1 个答案:

答案 0 :(得分:0)

这在O(n)时间内运行。请注意,每次我们推入堆栈时,由于将x分配给偶数值,我们会立即将其弹出;你是正确的,它只迭代一次。 while循环是完全没必要的,我们留下了

 (A[1...n]: array of integers) 
    stack S ← empty stack 
    for k ← 1 to n         
        push(S, A[k])
        pop(S)

显然是O(n)。