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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章