lc155 Min Stack

214 阅读1分钟

155. Min Stack

Easy

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.

思路:两个数组,一个数组nums用来作为栈,一个数组minnums用来存储最小数,压栈>一个数x的时候,x与minnums的栈顶元素比较,x<=minnums,x压入nums的同时压入minnu>ms,出栈时,两个栈同时pop,保证minnums栈顶元素一直为最小值

代码:python

class MinStack(object):
    
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.nums=[]
        self.minnums=[]

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        
        if len(self.nums) ==0:
            self.nums.append(x)
            self.minnums.append(x)
            return
        if  self.minnums[-1] < x:
            self.minnums.append(self.minnums[-1])
            print("minnums push"+str(self.minnums[-1]))
        else:
            self.minnums.append(x)
            print("nums push"+str(x))
        self.nums.append(x)
    def pop(self):
        """
        :rtype: None
        """        
        if len(self.nums) > 0:
            self.minnums.pop()
            return  self.nums.pop()
        else:
			return None




    def top(self):
        """
        :rtype: int
        """
        if  len(self.nums) >  0:
			return self.nums[-1]
        else:
			return None

    def getMin(self):
        """
        :rtype: int
        """
        if len(self.minnums) >  0:
			return self.minnums[-1]
        else:
			return None

# 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()