Use two stacks :

class MinStack {
private:
    stack<int> s, minS;
public:
    void push(int x) {
        if (minS.empty() || x <= minS.top()) {
            minS.push(x);
        }
        s.push(x);
    }

    void pop() {
        if (minS.top() == s.top()) {
            minS.pop();
        }
        s.pop();
    }

    int top() {
        return s.top();
    }

    int getMin() {
        return minS.top();
    }
};

 

A fancy algorithm, just use one stack and a number. But it will failed with INT_MIN and INT_MAX as overflow.

class MinStack {
private:
    int minValue;
    stack<int> s;
public:
    void push(int x) {
        if (s.empty()) {
            minValue = x;
            s.push(x);
        } else if (x < minValue) {
            s.push(2*x - minValue);
            minValue = x;
        } else {
            s.push(x);
        }
    }

    void pop() {
        if (s.top() < minValue) {
            minValue = 2*minValue - s.top();
        }
        s.pop();
    }

    int top() {
        if (s.top() < minValue) {
            return 2*minValue - s.top();
        }
        return s.top();
    }

    int getMin() {
        return minValue;
    }
};

 

posted on 2015-03-21 07:35  keepshuatishuati  阅读(136)  评论(0编辑  收藏  举报