题解 | 包含min函数的栈

包含min函数的栈

https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

边push,边记录min

#include <stack>
class Solution {
public:
    void push(int value) {
        stack1.push(value);
        if (stack2.empty() || stack2.top() > value) stack2.push(value);
        else stack2.push(stack2.top()); // 当前stack.size的最小元素
    }
    void pop() {
        stack1.pop();
        stack2.pop();
    }
    int top() {
        return stack1.top();
    }
    int min() {
        return stack2.top();
    }

private:
    stack<int> stack1;
    stack<int> stack2; // 仅int t不够哦;因为有pop
};

直接复制stack,然后比较、pop

#include <stack>
class Solution {
public:
    void push(int value) {
        stack1.push(value);
    }
    void pop() {
        stack1.pop();
    }
    int top() {
        return stack1.top();
    }
    int min() {
        stack<int> temp=stack1;
        int t = temp.top();
        temp.pop();
        while (!temp.empty()) {
            t = t < temp.top() ? t : temp.top();
            temp.pop();
        }
        return t;
    }

private:
    stack<int> stack1;
};

全部评论

相关推荐

09-22 22:22
中山大学 Java
双尔:赌对了,不用经历秋招的炼狱真的太好了,羡慕了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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