小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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.
Subscribe to see which companies asked this question。

分析

实现可求最小值的栈。

该特殊栈除了具有普通栈先进后出的特点,还必须可以有getMin函数求得实时的栈中最小元素。

利用一个辅助栈,保存当前元素对应栈的最小值。

AC代码

class MinStack {
public:
    void push(int x) {
        data.push(x);
        if (minData.empty())
            minData.push(x);
        else{
            if (minData.top() > x)
                minData.push(x);
            else
                minData.push(minData.top());
        }
    }

    void pop() {
        data.pop();
        minData.pop();
    }

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

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

private:
    stack<int> data;
    stack<int> minData;
};

GitHub测试程序源码

posted on 2015-10-31 13:16  Coding菌  阅读(118)  评论(0编辑  收藏  举报