我一直在努力解决编码面试中的问题,为一些面试做准备。我能够解决堆栈分类问题,但我很难找出如何推断时间复杂性。我的解决方案与本书提供的解决方案非常相似,我已经测试了一下,所以我确定它是正确的。任何对思维过程的深入分析都将非常感谢。这本书说它是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的常量时。我以为我在做什么,但现在我不确定。 – rocktheartsm4l
或将内部循环的分析为:1/n + 2/n + 3/n + 4/n + ...(n-1)/ n我们认为它只是n?我要睡觉很晚了< – rocktheartsm4l