剑指offer 面试题30. 包含min函数的栈 [简单]

与LeetCode155题一样

我的解题:

使用两个stack,一个正常保存数据,看一个保存第i个元素之前最小的元素

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> a,b;
    MinStack() {

    }
    
    void push(int x) {
        a.push(x);
        if(b.empty())   b.push(x);
        else{
            int t=b.top();
            b.push((x<t)?x:t);
        }
    }
    
    void pop() {
        a.pop();
        b.pop();
    }
    
    int top() {
        return a.top();
    }
    
    int min() {
        return b.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->min();
 */

发布了65 篇原创文章 · 获赞 1 · 访问量 488

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/105463747
今日推荐