美文网首页
[LeetCode]155. Min Stack

[LeetCode]155. Min Stack

作者: Eazow | 来源:发表于2016-05-25 18:33 被阅读117次

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.


#### 方法
这题不支持c,于是用python来实现。
注意不能用一个变量来记录stack的最小值,因为stack会被pop(),最小值可能会被取走,因此用了```self.mins```这个list来保存最小值,min[i]表示i个数的最小值。



#### python代码

class MinStack(object):

def __init__(self):
    """
    initialize your data structure here.
    """
    self.stack = []
    self.mins = []
    
def push(self, x):
    """
    :type x: int
    :rtype: void
    """
    min_val = self.getMin()
    if min_val==None or min_val>x:
        min_val = x
    self.mins.append(min_val)
    self.stack.append(x)
    
def pop(self):
    """
    :rtype: void
    """
    self.mins.pop()
    return self.stack.pop()
    
def top(self):
    """
    :rtype: void
    """
    return self.stack[-1]
    

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

minStack = MinStack()
minStack.push(-2)
minStack.push(0)
minStack.push(-3)
assert minStack.getMin()==-3
assert minStack.pop()==-3
assert minStack.top()==0
assert minStack.getMin()==-2

相关文章

网友评论

      本文标题:[LeetCode]155. Min Stack

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