Leetcode 155. 最小栈 C++ 双栈、单栈双解法。

双栈解法

class MinStack {
private:
    stack<int> s1;
    stack<int> s2;
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty() || x <= s2.top())     //s2为空 一定是小于等于号 因为可能会重复 pop会出问题
            s2.push(x);
    }
    
    void pop() {
        if(s1.top() == s2.top())
            s2.pop();
        s1.pop();
        
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
};

单栈解法

思路主要是存储一个pair结构,first代表当前压入的值,second代表当前的最小值。

class MinStack {
private:
    stack<pair<int,int>> s1;
 
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        if(s1.empty())
            s1.push(make_pair(x,x));
        else
        {
            s1.push(make_pair(x,min(x,s1.top().second)));
        }
        
    }
    
    void pop() {
        s1.pop();
        
    }
    
    int top() {
        return s1.top().first;
    }
    
    int getMin() {
        return s1.top().second;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章