155. Min Stack 求栈的最小值

Posted Long Long Journey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了155. Min Stack 求栈的最小值相关的知识,希望对你有一定的参考价值。

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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

  1. class MinStack(object):
  2. dataList = []
  3. def __init__(self):
  4. """
  5. initialize your data structure here.
  6. """
  7. self.dataList = []
  8. def push(self, x):
  9. """
  10. :type x: int
  11. :rtype: void
  12. """
  13. curMin = self.getMin()
  14. if curMin is None or x < curMin:
  15. curMin = x
  16. self.dataList.append([x,curMin])
  17. def pop(self):
  18. """
  19. :rtype: void
  20. """
  21. self.dataList.pop()
  22. if len(self.dataList) is 0:
  23. self.curMin = None
  24. def top(self):
  25. """
  26. :rtype: int
  27. """
  28. if len(self.dataList) is 0:
  29. return None
  30. return self.dataList[-1][0]
  31. def getMin(self):
  32. """
  33. :rtype: int
  34. """
  35. if len(self.dataList) is 0:
  36. return None
  37. return self.dataList[-1][1]
  38. # Your MinStack object will be instantiated and called as such:
  39. s = MinStack();
  40. s.push(0);
  41. s.push(1);
  42. s.push(0);
  43. s.getMin();
  44. s.pop();
  45. print(s.dataList)
  46. m = s.getMin();
  47. print(m)





以上是关于155. Min Stack 求栈的最小值的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode_155-Min Stack

LeetCode 155 Min Stack(最小栈)

LeetCode 155 Min Stack(最小栈)

Leetcode155. 最小栈(辅助栈)

Leetcode 155. Min Stack

155. Min Stack