Q155 Min Stack

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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容