1. 程式人生 > >155. Min Stack 求棧的最小值

155. Min Stack 求棧的最小值

gin pac append clas call onos all time self

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)



來自為知筆記(Wiz)

155. Min Stack 求棧的最小值