【每日一题Leetcode】155. 最小 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.

最初步的思路就是用list,插入和删除新数据很方便,但是在检索最小值的时候运行时间大吓人。

考虑优化思路:在插入新数据的时候进行对比,这个试了几种方法,比如增加一个列表来保存最小值和索引,但是每当列表中元素有变动的时候,索引都会改变,这种太麻烦因此pass掉了这种方式。

在论坛中有一种方法,将插入的元素和插入动作后当前stack元素中的最小值保存在元组中。因为stack是后进先出,这样在移除最上层的元素时,不用重新loop就可以提取top-1的最小值。

以下代码runtime=80ms,如果将insert改为append,runtime=53ms。

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        # use list as data type
        self.stack = []        
        
    def push(self, x):
        """
        :type x: int
        :rtype: void
        """        
        curr_min = self.getMin()
        if curr_min == None:
            curr_min = x
        else:
            curr_min = min(curr_min,x)                    
        self.stack.insert(0,(x,curr_min))
        
            
    def pop(self):
        """
        :rtype: void
        """
        self.stack.pop(0)
        

    def top(self):
        """
        :rtype: int
        """
        return self.stack[0][0]

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

参考:https://leetcode.com/problems/min-stack/discuss/49022/My-Python-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值