[LeetCode] - Min Stack O(1)最小棧

Min Stack

 

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
常見的面試題,要求實現最小棧。實現一個棧,能夠實現棧的基本操作,特色是能夠在O(1)的時間裏找出棧的最小值。


首先,想到的是,對於一個普通棧來說,不能實現O(1)找最小值。需要輔助,採用雙棧:

Real stack        Min stack

5  --> TOP        1
4                 1
1                 1
3                 2
2                 2
輔助棧每次存入當前最小值,並同步壓入和彈出即可。

但是以上問題是:Memory Limit Exceeded(消耗了2倍的空間)


優化: Min Stack 不必每次都存入,只需要存入最小值變化的狀態。

Real stack        Min stack

5  --> TOP        1
4                 2
1                 
3                 
2                 
所以每次出棧的時要比較一下,

入棧時 curr< = Min Stack Top 則MinStack 也要入棧  

如果Real Stack top == Min Stack top  則 Min Stack 也需要pop()

注意:最小值可能會多次入棧的問題。

class MinStack{
public:
    void push(int x) {
         S.push(x);
         if(MinS.empty() || x<=MinS.top())
             MinS.push(x);
    }

    void pop(){
        int temp=S.top();
        S.pop();
        if(temp == MinS.top())
            MinS.pop();
    }

    int top(){
        return S.top();
    }
    int getMin(){
        return MinS.top();
    }
private:
    stack<int> S,MinS;
};





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