【发布时间】:2015-03-28 04:21:27
【问题描述】:
我无法理解 Big-O 表示法。这是我写的一个算法,它应该是 (C++) Stack 的 size() 函数的替代方案,我需要在堆栈中有 n 个元素的假设下确定它的运行时间当它被调用时。
Algorithm size():
Input: none
Output: A constant value of the size of an n-element stack.
Let V be a vector of n type objects.
Let S be the name of the stack that is being operated on by this function.
K ← 0
V
while !empty()
V.push_back(top()) //Keep track of elements in V
S.pop() //Remove element from stack
K ← K + 1 //Count the size of the stack
return K //Return the size of the stack
for i ← K – 1, i > 0, i-- do
S.push(V[i]) //Retain initial contents of stack
请纠正我的错误:
在 K ← 0 行,我认为这是一个 O(1) 操作。
创建向量 V 也是一个 O(1) 操作。
while 循环是一个 O(n) 操作,因为它一直运行到清空包含 n 内容的堆栈。
将值推回 V 是一个 O(n) 操作。
从堆栈 S 中弹出内容是一个 O(n) 操作。
返回 K 是一个 O(1) 操作。
for 循环是一个 O(n) 操作。
将内容推回 S 是一个 O(n) 操作。
【问题讨论】:
-
math.stackexchange.com 或 cs.stackexchange.com 会是关于 Big-Oh 表示法问题的更好地方。
-
除非你必须复制整个向量或堆栈,否则推入和弹出元素应该是 O(1)。
-
for循环永远不会被执行,因为它在return语句之后。 -
在我看来您的算法有点错误,但个别复杂性非常正确。通常,您会将整体复杂性总结为组件复杂性中“最差”的,在您的情况下为 O(n)。
-
@JerryCoffin 除了Barmar指出的return语句之外,算法有什么问题?
标签: c++ algorithm stack big-o asymptotic-complexity