Sword finger: the stack containing min function (min stack)

Keywords: PHP less Java

Title Description

Design a stack that supports push, pop, top and other operations and can retrieve the minimum elements in O(1) time.

  • push(x) - insert element x into the stack
  • pop() - remove top element
  • top() - get the top element of the stack
  • getMin() - get the smallest element in the stack

Example

MinStack minStack = new MinStack();
minStack.push(-1);
minStack.push(3);
minStack.push(-4);
minStack.getMin();   --> Returns -4.
minStack.pop();
minStack.top();      --> Returns 3.
minStack.getMin();   --> Returns -1.

 

 

solution

Two stacks are defined, one is the auxiliary stack for storing the least number of sequences.

When pressing the stack, first press the element x into stack1. Then judge the situation of stack2:

  • If the stack2 stack is empty or the top element of the stack is greater than x, press X into stack2.
  • If stack2 stack is not empty and the stack element is less than x, then the top element is pressed repeatedly.

When getting the minimum element, just get the top element from stack2.

 

import java.util.Stack;

public class MinStack {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    
    public MinStack(){
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    public void push(int x){
        stack1.push(x);
        if(stack2.isEmpty() || stack2.peek()>x)
            stack2.push(x);
        else
            stack2.push(stack2.peek());
    }
    
    public void pop(){
        stack1.pop();
        stack2.pop();
    }
    
    public int top(){
        return stack1.peek();
    }
    
    public int getMin(){
        return stack2.peek();
    }
}
public static void main(String[] args) {
    MinStack obj = new MinStack();
    obj.push(-1);
    obj.push(3);
    obj.push(-4);
    obj.push(0);
    obj.pop();
    int param_3 = obj.top();
    int param_4 = obj.getMin();
    System.out.println(param_3+ " "+param_4);
}

Posted by nalleyp23 on Fri, 25 Oct 2019 13:13:25 -0700