码迷,mamicode.com
首页 > 其他好文 > 详细

155. Min Stack 求栈的最小值

时间:2017-07-31 23:27:25      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:datalist   obj   pen   最小值   space   otto   ant   led   rmi   

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 求栈的最小值

标签:datalist   obj   pen   最小值   space   otto   ant   led   rmi   

原文地址:http://www.cnblogs.com/xiejunzhao/p/7266226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!