【leetcode】Min Stack -- python版

题目描述:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.

解题思路:

这个问题挺简单(确实leetcode给的评级也是easy),但是还真是遇上了不少的问题。
首先,这道题目我们的想法是如何去做到这个特殊的getMin,想到的方法当然是空间换时间啦,那么用什么空间呢?当然是另一个栈啦,所以我们就有了这么一个想法:用另一个栈来记录当前最小值,那么查找最小值就不需要遍历了,这样就实现了时间复杂度和空间复杂度都是O(n)。的确这个想法已经很不错了,用java(官方题解就是这个版本)和C++(亲测)。但是我用python就MLE了,让我纠结了好久。
所以在没办法就要优化内存了,这里采用的方法是在minStack中插值的时候对相同的值不重复插入,而是记录他的次数,终于AC

MLE

 1 class MinStack:

 2     def __init__(self):

 3         self.stack = []

 4         self.minStack = []

 5     # @param x, an integer

 6     # @return an integer

 7     def push(self, x):

 8         self.stack.append(x)

 9         if len(self.minStack) == 0 or self.minStack[-1] >= x:

10             #print 'minn change'

11             self.minStack.append(x)

12  

13     # @return nothing

14     def pop(self):

15         p = self.stack.pop()

16         #print 'pop ' , p

17         if p == self.minStack[-1]:

18             #print 'minn pop'

19             self.minStack.pop()

20 

21     # @return an integer

22     def top(self):

23         return self.stack[-1]

24 

25     # @return an integer

26     def getMin(self):

27         return self.minStack[-1]

AC

 1 class MinStack:

 2     def __init__(self):

 3         self.stack = []

 4         self.minStack = []

 5         #self.minStack.append(0)

 6     # @param x, an integer

 7     # @return an integer

 8     def push(self, x):

 9         self.stack.append(x)

10         if len(self.minStack) == 0 or self.minStack[-1][0] > x:

11             #print 'minn change'

12             self.minStack.append((x,1))

13         elif x == self.minStack[-1][0]:

14             self.minStack[-1] = (x, self.minStack[-1][1] + 1)

15  

16     # @return nothing

17     def pop(self):

18         p = self.stack.pop()

19         #print 'pop ' , p

20         if p == self.minStack[-1][0]:

21             if self.minStack[-1][1] > 1:

22                 #print 'minn pop'

23                 self.minStack[-1] = (self.minStack[-1][0], self.minStack[-1][1] - 1)

24             else:

25                 self.minStack.pop()

26 

27     # @return an integer

28     def top(self):

29         return self.stack[-1]

30 

31     # @return an integer

32     def getMin(self):

33         #print self.minStack

34         return self.minStack[-1][0]

 

你可能感兴趣的:(LeetCode)