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.

我的解法——单栈(AC)

  • 一个栈
  • 时间时间复杂度均为O(logn),空间复杂度为O(1)。
  • Beat29%
class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)

    def pop(self):
        """
        :rtype: void
        """
        res = self.stack[len(self.stack) - 1]
        self.stack = self.stack[:len(self.stack) - 1]
        return res

    def top(self):
        """
        :rtype: int
        """
        return self.stack[len(self.stack) - 1]

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.stack)


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

最优解法——双栈

  • 主要是模拟写一个最小栈。要注意push时可能会输入null。需要使用双栈实现,一个保存数据,一个保存最小值。由于随着数据出栈,最小值是不断变化的,因此需要一个最小值栈来保存最小值。
class MinStack {
private:
    std::stack<int> stack;
    std::stack<int> min_stack;
public:
    void push(int x) {
        stack.push(x);
        if (min_stack.empty() || ((!min_stack.empty()) && x <= min_stack.top())) {  //NOTE: 是“小于等于”,不是“小于”
            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();
    }
};

参考答案

  • https://blog.csdn.net/zj443108444/article/details/50848155