【LeetCode】155. Min Stack

原题链接:https://leetcode.com/problems/min-stack/tabs/description

要求:

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.

想法:

这种按照题目要求设计栈的问题很常见,一般可以直接用到C++标准库中的stack<>以及对应的操作,做的多了自然就有自己的想法了。

代码如下:

class MinStack {
private:
    stack<int> mystack;
    stack<int> min;        
public:
    void push(int x) {
        mystack.push(x);
        if (min.empty() || x < getMin()) min.push(x);
    }
    
    void pop() {
        if (mystack.top() == getMin()) min.pop();
        mystack.pop();
    }
    
    int top() {
        return mystack.top();
    }
    
    int getMin() {
        return min.top();
    }
};

这段代码挺容易理解的,不过提价了竟然说超时了,仔细检查发现在push()中比较x和最小值时忘掉了相等的情况,导致若是相等时没有最小值,将代码中的小于号改成小于等于就OK了!

posted on 2017-07-28 16:22  小言大妖  阅读(103)  评论(0)    收藏  举报