【leetcode】155最小棧

題目描述

https://leetcode-cn.com/problems/min-stack/

思路

getMin() —— 檢索棧中的最小元素。需要輔助棧保存最小值。其他和棧功能相同。

也可以設置變量記錄最小值。

代碼實現:

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty() || x <= s2.top())
            s2.push(x);
    }
    
    void pop() {
        if(s1.top() == s2.top()) s2.pop();
        s1.pop();
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
private:
    stack<int> s1,s2;//s1棧來按順序存儲 push 進來的數據,s2用來存出現過的最小值
};

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

參考:https://www.cnblogs.com/grandyang/p/4091064.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章