【问题标题】:What is the worst-case time complexity of dequeuing from a two-stack queue?从两个堆栈队列中出列的最坏情况时间复杂度是多少?
【发布时间】:2013-10-21 01:04:58
【问题描述】:

我的作业要求我确定以下算法的最坏情况运行时间。入队很容易。这只是恒定的(我希望,否则我会觉得很愚蠢)

第二个令人困惑。我昨天问了一个类似的问题,得到了很多非常有用的答案。我会尽力而为。

Algorithm enqueue(o)
    in stack.push(o)

Algorithm dequeue()
    while (! in stack.isEmpty()) do    // this just checks for an empty stack, so O(1)
        out stack.push(in stack.pop()) // this do loop runs for as many times as values in the stack, so it is O(N)

    if (out stack.isEmpty()) then
        throw a QueueEmptyException    // this is just an exception, so I assume it is O(1) 

    return_obj ←  out stack.pop()      // I think the rest of the program is linear.
                                       // Although without actually coding it out, I'm not 100% sure I even understand what it does.
    while (! out stack.isEmpty()) do

    in stack.push(out stack.pop())
    return return_obj;

【问题讨论】:

  • 这看起来不像 C++
  • 我认为是伪代码。

标签: data-structures stack queue big-o


【解决方案1】:

查看此问题的一种方法是计算推送和弹出的次数。如果您的队列中有 n 个元素,则实现将执行 n 次推送和 n 次弹出以将in 传输到out。然后它会弹出一次以摆脱最后一个元素,然后再进行 n - 1 次推送和 n - 1 次弹出以将 out 放回 in。这是总共 Θ(n) 的 push 和 pop。每个 push 和 pop 需要 Θ(1) 时间(或者至少, n push 和 n pops 需要 Θ(n) 时间),因此堆栈操作完成的总工作是 Θ(n)。那里还有 O(1) 额外的工作,比如错误处理等。因此,完成的总工作是 Θ(n)。

希望这会有所帮助!

【讨论】:

  • 问题中的实现与您所描述的不同,出队总是将元素从in 移动到out 并再次返回。这导致出队的最佳情况复杂度为 O(n)。
【解决方案2】:

从链表的前面删除一个节点需要恒定的时间。但是,找到链表的最后一个节点需要线性时间(除非我们小心维护对它的引用)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多