我对howmework有这个问题:
使用 3 个堆栈实现双端队列。Deque 有这些操作:InsertHead、InsertTail、DeleteHead、DeleteTail。证明每个操作的摊销时间为 O(1)。
我尝试将问题视为河内问题。因此,让我们将堆栈称为:L(左),M(中),R(右)。
伪代码实现:
InsertHead(e):
L.push(e);
DeleteHead(e):
L is empty:
while R is not empty:
pop and insert the element to M;
pop M;
while M is not empty:
pop and insert the element to R;
L is not empty:
L.pop(e);
InsertTail 和 DeleteTail 与上述实现原理相同。如何证明摊销时间为 O(1)?因为 L 中可以有 N 个元素,并且 wile 循环将花费 O(n),现在如果我调用 deleteHead N 次来计算摊销时间,复杂度不会是 O(n^2)?
有人可以帮助我如何证明上述实现在摊销时间内需要 O(1) 吗?