题解 设计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;
    }
};
全部评论

相关推荐

11-23 15:33
已编辑
门头沟学院 Java
CUTMR:换账号试试重启推荐算法,我换账号之后回复率还不错,约莫有个20%左右的消息回复率,前几页、主动招呼的HR也开始符合我期望薪资,此前的大号从招呼、回复、前几页的岗位薪资在涨幅30%+以上 用着用着聊着聊着就变成-20%,而且我开通会员之后直接0面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务