# 155. Min Stack

## 1.問題

* 設計一個stack可以支援pop最小值 (常數時間)

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJczhf3NUWcYWJLNAJC%2F-LJd-foqZDlBq5Ay9Ee5%2F2018081103.jpg?alt=media\&token=3c70aed5-1232-49c3-9433-a90f45ceac05)

## 2.想法

* 利用stack後進先出的特性

## 3.程式碼

```
class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        if (!minStack.empty()) {
            int m = (x < minStack.top()) ? x : minStack.top();
            minStack.push(m);
        } else {
            minStack.push(x);
        }
        genStack.push(x);
    }
    
    void pop() {
        minStack.pop();
        genStack.pop();
    }
    
    int top() {
        return genStack.top();
    }
    
    int getMin() {
        return minStack.top();
    }
private:
    stack<int> minStack;
    stack<int> genStack;
};

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

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJczhf3NUWcYWJLNAJC%2F-LJd04vBSTTywojjyoTk%2F2018081104.jpg?alt=media\&token=ff7579e2-7a8e-421e-8348-f1a079421900)
