剑指Offer30-包含min函数的栈

剑指Offer30-包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

示例:


MinStack minStack = new MinStack();

minStack.push(-2);

minStack.push(0);

minStack.push(-3);

minStack.min();   --> 返回 -3.

minStack.pop();

minStack.top();      --> 返回 0.

minStack.min();   --> 返回 -2.

提示:


各函数的调用总次数不超过 20000 次

来源:力扣(LeetCode)

链接:力扣

一解

本题难点在于“调用 min”的时间复杂度为O(1),可利用辅助栈存放最小值:

  • 栈A:基本栈操作,push,pop,top

  • 栈B:存放“栈A”中最小元素

比如将 -2, 0, -3 入栈:


class MinStack:

    def __init__(self):

        """

        initialize your data structure here.

        """

        self.A, self.B = [], []

    def push(self, x: int) -> None:

        self.A.append(x)

        # 如果x是最小元素,存入 B

        if not self.B or self.B[-1] >= x:

            self.B.append(x)

    def pop(self) -> None:

        # A 出栈的是最小元素,将其从 B 出栈

        if self.A.pop() == self.B[-1]:

            self.B.pop()

    def top(self) -> int:

        return self.A[-1]

    def min(self) -> int:

        return self.B[-1]

# Your MinStack object will be instantiated and called as such:

# obj = MinStack()

# obj.push(x)

# obj.pop()

# param_3 = obj.top()

# param_4 = obj.min()

class MinStack:

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

    def min(self):
        if self.B:
            return self.B[-1]

    def push(self, val):
        self.A.append(val)
        if not self.B or val <= self.B[-1]:
            self.B.append(val)

    def pop(self):
        if self.B:
            if self.A.pop() == self.B[-1]:
                self.B.pop()

    def top(self):
        if self.A:
            return self.A[-1]


min_stack = MinStack()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
assert min_stack.top() == -3
assert min_stack.min() == -3
min_stack.pop()
assert min_stack.top() == 0
assert min_stack.min() == -2