美文网首页
Q155 Min Stack

Q155 Min Stack

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:33 被阅读9次

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.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.
解题思路:

此题为栈的基本操作,加了一个在 O(1) 的时间返回最小值的功能。

具体做法先在初始化的时候定义一个栈。在每次压栈(push)的过程中,先取出最小值(getMin)与当前压入栈的值比较,更新当前最小值。最后,把当前压入值和当前最小值都压入栈中,方便在得到最小值(getMin)的时候直接取出即可。

注意点:

pop() 之前要确保栈不能为空;top() 是取出栈顶值,而不是删除栈顶元素。

Python实现:
class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []  # 定义一个栈

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        curMin = self.getMin()  # 取出最小值
        if curMin == None or x < curMin:
            curMin = x
        self.stack.append((x, curMin))   # 同时保存最小值
        
    def pop(self):
        """
        :rtype: void
        """
        if len(self.stack) != 0:  # 判断栈是否为空
            self.stack.pop()[0]

    def top(self):
        """
        :rtype: int
        """
        if len(self.stack) == 0:  # 判断栈是否为空
            return None
        return self.stack[-1][0]

    def getMin(self):
        """
        :rtype: int
        """
        if len(self.stack) == 0:
            return None
        return self.stack[-1][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.getMin()

obj = MinStack()
obj.push(-2)
obj.push(1)
obj.push(-3)
print(obj.getMin())  # -3
obj.pop()
print(obj.top())  # 1
print(obj.getMin())  # -2

相关文章

  • Q155 Min Stack

    Design a stack that supports push, pop, top, and retrievi...

  • Min Stack

    Easy, Stack Question: 设计一个支持push, pop, top, getMin的堆栈。时间复...

  • Min Stack

    复盘: 可以不初始化大小 , 用append可以自动扩容 边界条件判断 这样会减到负值 画图: pesudo co...

  • Min Stack

    Min Stack Design a stack that supports push, pop, top, an...

  • Leetcode-155Min Stack

    155. Min Stack && 剑指offer-包含min函数的栈 Design a stack that s...

  • Cool Leetcode

    1、Min Stack Design a stack that supports push, pop, top, ...

  • leetcode:155. Min Stack

    155. Min Stack Description Design a stack that supports p...

  • Introduction to Full Stack

    Full stack Introduction to Full Stack15 min preparation A...

  • 155 Min Stack

    Design a stack that supports push, pop, top, and retrievi...

  • 0155 Min Stack

    Design a stack that supports push, pop, top, and retrievi...

网友评论

      本文标题:Q155 Min Stack

      本文链接:https://www.haomeiwen.com/subject/fhkbtftx.html