leetcode_155_最小栈

设计一个支持 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.
class MinStack {
public:
    /** initialize your data structure here. */
    std::stack<int> stack;
    std::stack<int> min_stack;
    MinStack() {
        
    }
    
    void push(int x) {
        stack.push(x);
        if (min_stack.empty() || ((!min_stack.empty()) && x <= min_stack.top())) 
            min_stack.push(x);
    }
    
    void pop() {
         if (!stack.empty())
         {
            if (stack.top() == min_stack.top())
                min_stack.pop();
            stack.pop();
         }
    }
    
    int top() {
        if (!stack.empty())
            return stack.top();
    }
    
    int getMin() {
        if (!min_stack.empty())
            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();
 */

该题设计两个栈,一个栈是正常的栈s,而另一个是存最小值的栈sm

在push时要判断sm是否为空,如果为空或者非空但是栈顶元素大于等于插入值的 需要在sm中插入x

同样地在pop时,s的元素被删除了,那么sm中的也应该被删除。


猜你喜欢

转载自blog.csdn.net/snow_jie/article/details/80936003
今日推荐