V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zl939144892
V2EX  ›  算法

关于网上最小栈解法的疑问

  •  
  •   zl939144892 · 2018-02-28 13:42:02 +08:00 · 2309 次点击
    这是一个创建于 2220 天前的主题,其中的信息可能已经有所发展或是发生改变。
    先上链接 https://www.cnblogs.com/loveyixiang/p/6030920.html
    邮个疑问: 就是当 B 栈的数据先出完了,再怎么获取最小值呢?
    ai277014717
        1
    ai277014717  
       2018-02-28 16:50:40 +08:00
    B 不会出完,保证 B 跟 A 栈元素个数一样。当初的面试题啊,一脸蒙蔽
    ai277014717
        2
    ai277014717  
       2018-02-28 17:11:26 +08:00
    `class MinStack {
    public:
    /** initialize your data structure here. */
    stack<int> sta;
    stack<int> stb;
    MinStack() {

    }

    void push(int x) {
    sta.push(x);
    if(stb.size()==0){
    stb.push(x);
    }
    else {
    if(stb.top()>x){
    stb.push(x);
    }
    else {
    stb.push(stb.top());
    }
    }
    }

    void pop() {
    sta.pop();
    stb.pop();
    }

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

    int getMin() {
    return stb.top();
    }
    };`
    刚刚水了一题
    ai277014717
        3
    ai277014717  
       2018-02-28 17:18:36 +08:00
    ```
    class MinStack {
    public:
    /** initialize your data structure here. */
    stack<int> sta;
    stack<int> stb;
    MinStack() {

    }

    void push(int x) {
    sta.push(x);
    if(stb.size()==0){
    stb.push(x);
    }
    else {
    if(stb.top()>x){
    stb.push(x);
    }
    else {
    stb.push(stb.top());
    }
    }
    }

    void pop() {
    sta.pop();
    stb.pop();
    }

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

    int getMin() {
    return stb.top();
    }
    };
    ```
    试试 markdown
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3279 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:15 · PVG 22:15 · LAX 07:15 · JFK 10:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.