【发布时间】:2017-01-24 05:42:18
【问题描述】:
我一直在解决破解编码面试中的问题,为一些面试做准备。我能够解决堆栈排序问题,但我很难弄清楚如何推理时间复杂度。我的解决方案与书中提供的解决方案非常相似,并且我已经对其进行了相当多的测试,所以我确信它是正确的。任何对分析该算法的思考过程的见解将不胜感激。这本书说它是O(n ^ 2)。这是算法:
def sort_stack(stack):
temp_stack = Stack()
while not stack.is_empty():
v = stack.pop()
if temp_stack.is_empty() or temp_stack.peek() <= v:
temp_stack.push(v)
else:
while not temp_stack.is_empty() and temp_stack.peek() > v:
stack.push(temp_stack.pop())
temp_stack.push(v)
while not temp_stack.is_empty():
stack.push(temp_stack.pop())
附带说明:我使用这种方法对堆栈进行排序,以便在问题的约束范围内。我知道存在更快的解决方案。
提前谢谢你。
【问题讨论】:
-
外循环至少有 n 次迭代,我知道。内部循环可能有 0 和 temp_stack.size 之间的迭代,具体取决于值。在最坏的情况下,原始堆栈已经排序,我们将有 0 + 1 + 2 + 3 + ... (n -1) 次迭代......但我认为总和最终为 n(n + 1) / 2 当我们忽略本身为 n^2 的常量时。我以为我在做某事,但现在我不确定。
-
或者内部循环的分析是:1/n + 2/n + 3/n + 4/n + .... (n-1)/n 我们认为只是吗?时间不早了,我要睡觉了>.
标签: python algorithm sorting stack big-o