题解 设计getMin功能的栈

设计getMin功能的栈

http://www.nowcoder.com/practice/c623426af02d4c189f92f2a99647bd34

使用两个栈:元素栈和最小栈,最小栈随时记录当前状态栈的最小值
元素栈出栈,最小栈也一块出栈;元素栈入栈,最小栈入栈当前栈状态的最小值

class Solution {
public:
    stack<int> s, s_min;
    vector<int> getMinStack(vector<vector<int> >& op) {
        vector<int> res;
        for(int i=0; i<op.size(); ++i){
            if(op[i].size() == 2)
                Push(op[i][1]);
            else
                op[i][0]==2?Pop():res.push_back(getMin());
        }
        return res;
    }
    void Push(int x) {
        s.push(x);
        s_min.empty() ? s_min.push(x) : x < s_min.top() ?
            s_min.push(x) : s_min.push(s_min.top());
    }
    void Pop(){
        if(s.empty())
            return ;
        s.pop();
        s_min.pop();
    }
    int getMin(){
        if(!s.empty())
            return s_min.top();
        else
            return -1;
    }
};
全部评论

相关推荐

头像
今天 09:14
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务