LeetCode 155. Min Stack

解題思路:利用stack 重寫 MinStack()

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int>res;
    stack<int>min;
    
    void push(int x) {
        res.push(x);
        if(min.empty()||x<=min.top())
            min.push(x);
    }
    
    void pop() {
        if (!min.empty()) {
            if (res.top() == min.top())
                min.pop();
            res.pop();
        }
    }
    
    int top() {
        return res.top();
    }
    
    int getMin() {
        return min.top();
    }
};


發佈了82 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章