The stack containing the min function

Define the data structure of the stack. Please implement a min function in this type that can get the smallest element of the stack. In this stack, the time complexity of calling min, push and pop is O(1).

Example:

MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.min(); –> return -3.minstack.pop (); minStack.top(); –> return 0. Minstack.min (); — — > to return to 2.

Tip:

The total number of calls for each function does not exceed 20000 times

Answer:

java

class MinStack {
    Stack<Integer> A, B;
    public MinStack(a) {
        A = new Stack<>();
        B = new Stack<>();
    }
    public void push(int x) {
        A.add(x);
        if(B.empty() || B.peek() >= x)
            B.add(x);
    }
    public void pop(a) {
        if(A.pop().equals(B.peek()))
            B.pop();
    }
    public int top(a) {
        return A.peek();
    }
    public int min(a) {
        returnB.peek(); }}Copy the code

python

class MinStack(object):

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


    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.resA.append(x)
        if not self.resB or self.resB[-1]>=x:
            self.resB.append(x) 



    def pop(self):
        """
        :rtype: None
        """
        if self.resA.pop(a)==self.resB[- 1]:
            self.resB.pop()


    def top(self):
        """ :rtype: int """
        return self.resA[- 1]


    def min(self):
        """ :rtype: int """
        return self.resB[- 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.min()
Copy the code