1. 程式人生 > 其它 >【LeetCode】C++ :簡單題 - 棧 155. 最小棧

【LeetCode】C++ :簡單題 - 棧 155. 最小棧

技術標籤:LeetCodeleetcode演算法

155. 最小棧

難度簡單759

設計一個支援pushpoptop操作,並能在常數時間內檢索到最小元素的棧。

  • push(x)—— 將元素 x 推入棧中。
  • pop()—— 刪除棧頂的元素。
  • top()—— 獲取棧頂元素。
  • getMin()—— 檢索棧中的最小元素。

示例:

輸入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

輸出:
[null,null,null,null,-3,null,0,-2] 解釋: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.

提示:

  • poptopgetMin操作總是在非空棧上呼叫。

棧的實現形式有兩種,一個種是連結串列,另一種是陣列。

面對這道題我用了笨笨的方法,即用陣列來儲存棧。

class MinStack {
public:
    /** initialize your data structure here. */
    // stack<int> x_stack;
    vector<int> x_stack;

    // stack<int> min_stack;
    
    MinStack() {
        // min_stack.push(INT_MAX);    
    }
    
    void push(int x) {
        x_stack.push_back(x);
        // min_stack.push(min(min_stack.top(), x));
    }
    
    void pop() {
        x_stack.pop_back();
        // min_stack.pop();
    }
    
    int top() {
        return x_stack[x_stack.size() - 1];
    }
    
    int getMin() {
        if(x_stack.size() <= 0){
            return INT_MIN;
        }

        int min = x_stack[0];
        for(int i = 1; i <x_stack.size(); i++){
            if (min > x_stack[i]){
                min = x_stack[i];
            }
        }
        return min;
    }
};

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

官方題解用到的是兩個棧,一個輔助棧,一個最小棧。對輔助棧操作進棧出站和輸入的資料一致,對最小棧的進棧是每次將棧頂的值和當前值進行比較取最小值,就是說最小棧中的元素是當前的最小值,且會重複進棧。這樣能夠使取得最小值時直接獲得。

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> x_stack;
    stack<int> min_stack;
    
    MinStack() {
        min_stack.push(INT_MAX);    
    }
    
    void push(int x) {
        x_stack.push(x);
        min_stack.push(min(min_stack.top(), x));
    }
    
    void pop() {
        x_stack.pop();
        min_stack.pop();
    }
    
    int top() {
        return x_stack.top();
    }
    
    int getMin() {
        return min_stack.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->getMin();
 */

是的,事實就是,我的辦法執行時間相比太長了。