# 155.Min Stack

难度:Easy

**155.Min Stack**

> 设计一个支持 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.

要设计一个支持返回最小值的栈，可以使用两个栈实现：一个支持push和pop、top等操作，另一个保存每次的最小值。

```
class MinStack {
private:
        stack<int> num;
        stack<int > m;
public:
    /** initialize your data structure here. */
    MinStack() {
 
        
    }
    
    void push(int x) {
        if(num.empty()) m.push(x);
        else m.push(min(m.top(),x));
        num.push(x);
        
        
    }
    
    void pop() {
        num.pop();
        m.pop();
    }
    
    int top() {
        return num.top();
        
    }
    
    int getMin() {
        return m.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();
 */
```

> 执行用时 :36 ms, 在所有 C++ 提交中击败了97.28%的用户\
> 内存消耗 :16.9MB, 在所有 C++ 提交中击败了69.68%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/155.min_stack.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
