1. 程式人生 > >LeetCode155 最小棧

LeetCode155 最小棧

題目

設計一個支援 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。 push(x) – 將元素 x 推入棧中。 pop() – 刪除棧頂的元素。 top() – 獲取棧頂元素。 getMin() – 檢索棧中的最小元素。

示例

MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.

C++程式碼

用兩個棧來存放資料,一個儲存所有壓入的資料(nums),另一個儲存當前最小的值(minnums)(top()的值始終為最小)。 注意,當呼叫pop()函式時,要考慮到儲存最小值的棧(minnums)是否也需要pop。 判斷方法為其top()是否等於nums.top(); minStack.push(-2); minStack.push(0); minStack.push(-3);

-3
0 -3
-2 -2

minStack.pop();

0
-2 -2
class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() 
    {
      
    }
    void push(int x) 
    {
        nums.push(x);
        if(minnums.empty()||x<=getMin()) minnums.push(x);
    }
    void pop() 
    {
        if(nums.top()==getMin()) minnums.pop(); 
        nums.pop();
    }
    int top() 
    {
        return nums.top();
    }
    int getMin() 
    {
        return minnums.top();
    }
private:
    stack<int> nums;
    stack<int> minnums;   
};