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.

利用栈来存储最小值

  1. class MinStack {
  2. public:
  3. void push(int x) {
  4. data.push(x);
  5. if(min.empty()) min.push(x);
  6. else if(x<=min.top()) {
  7. min.push(x);
  8. }
  9. }
  10. void pop() {
  11. if(data.empty()) {
  12. return;
  13. }
  14. int top = data.top();
  15. if(top == min.top()) {
  16. min.pop();
  17. }
  18. data.pop();
  19. }
  20. int top() {
  21. if(!data.empty())
  22. return data.top();
  23. return -1;
  24. }
  25. int getMin() {
  26. if(min.empty()) {
  27. return -1;
  28. }
  29. return min.top();
  30. }
  31. private:
  32. stack<int> data;
  33. stack<int> min;
  34. };
posted @ 2014-12-16 15:03  purejade  阅读(79)  评论(0)    收藏  举报