python 的 list 效率底下?

2014-11-11 19:49:55 +08:00
 janstk

题目

Design a stack that supports push, pop, top, and retrievingthe minimum element in constant time.

答案:

class MinStack:
    def __init__(self):
        self.L=[]
    def pop(self):
        return self.L.pop()
    def push(self,x):
        self.L.append(x)
    def top(self):
        return self.L[-1]
    def getMin(self):
        tmpL = self.L[:]
        tmpL.sort()
        return tmpL[0]

每次提示答案都超时…表吐槽,表示刚学python

8296 次点击
所在节点    Python
43 条回复
ryanking8215
2014-11-12 16:00:56 +08:00
@zhchbin 确实看错了,:)
dingyaguang117
2014-11-12 16:52:41 +08:00
pair的单栈,哈哈 就是比较浪费空间,有些最小值不必要存~
push:
-> push tuple(num, min)

pop:
-> pop tuple(num, min)
janstk
2014-11-12 17:01:00 +08:00
好吧终于过了,感谢上面回复的各位。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://ex.noerr.eu.org/t/145709

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX