【发布时间】:2015-06-02 15:22:59
【问题描述】:
根据下面引号中的规范,实现了一个队列(该语言使用 Ruby,但希望每个人都可以阅读)。
使用堆栈实现队列。也就是写入队和出队 仅使用推送和弹出操作。
在性能方面,入队应该是O(1),但出队可能是 最坏情况 O(n)。就摊销时间而言,出队应该是 O(1)。 证明您的解决方案可以做到这一点。
class StackQueue
def initialize
@in, @out = [], []
end
def enqueue(value)
@in << value
end
def dequeue
if @out.empty?
@out << @in.pop until @in.empty?
end
@out.pop
end
end
我想知道,您如何证明出队的摊销时间? 谢谢!
【问题讨论】:
-
对#1 的明显回答:
shift不在规范允许的方法集中,即push和pop。
标签: performance data-structures queue