Summary of leetcode brushing

Keywords: network

2019/8/3: Minimum stack

Problem description

Design a stack that supports push, pop, top operations and can retrieve the smallest elements in a constant time.

push(x) - Push element x into the stack.
pop() - delete the element at the top of the stack.
top() - Gets the top element of the stack.
getMin() - Retrieves the smallest element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
MinStack. getMin (); --> Return - 3.
minStack.pop();
MinStack. top (); --> Return 0.
MinStack. getMin (); --> Return - 2.

Source: LeetCode
Links: https://leetcode-cn.com/problems/min-stack
Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Complete code

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.item = []

    def push(self, x: int) -> None:
        self.item.append(x)

    def pop(self) -> None:
        if len(self.item) > 0:
            return self.item.pop()
        else:
            return 0

    def top(self) -> int:
        if len(self.item) != "":
            return self.item[len(self.item)-1]
        else:
            return 0

    def getMin(self) -> int:
        if len(self.item) > 0:
            return min(self.item)
        else:
            return 0


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


Well, it feels like a little bit of a problem. After referring to other people's code, we find that we need to use two lists to achieve it. Because the minimum value of the stack is required to be retrieved in a constant time, and min() takes a long time, we introduce minStack list to store the minimum value:

class MinStack(object):
 
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []       
        self.minStack = []
 
    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        if not self.minStack or self.minStack[-1]>=x:
            self.minStack.append(x)
 
    def pop(self):   
        """
        :rtype: void
        """
        if self.minStack[-1]==self.stack[-1]:
            del self.minStack[-1]
        self.stack.pop()
 
    def top(self):
        """
        :rtype: int
        """
        return self.stack[-1]
        
    def getMin(self):
        """
        :rtype: int
        """
        return self.minStack[-1]

Posted by vincente on Fri, 11 Oct 2019 10:13:03 -0700