Sword Finger Offer Interview Question 30. Stack with min function [simple]

Same as LeetCode155

My solution:

Use two stacks, one to save data normally, see the smallest element before saving the i-th element

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();
 */

Published 65 original articles · Like1 · Visits 488

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105463747