【leetcode】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.

Solution:  若只维护一个栈stk,在每次getMin的时候检索stk需要两倍的临时空间,倒两次,故用两个栈,一个stk,一个min

 1 class MinStack {
 2 public:
 3     void push(int x) {
 4         stk.push(x);
 5         if(min.empty()||x<=min.top())min.push(x);       //if的两个判断条件顺序不能替换,否则stk添加第一个元素后getMin出错
 6     }
 7     void pop() {
 8         if(stk.top()==min.top()){
 9             stk.pop();
10             min.pop();
11         }else
12             stk.pop();
13     }
14     int top() {
15         return stk.top();
16     }
17     int getMin() {
18         return min.top();
19     }
20 private:
21     stack<int> stk;
22     stack<int> min;
23 };

 

posted @ 2015-08-08 20:14  irun  阅读(118)  评论(0编辑  收藏  举报