[LeetCode 155] Min Stack

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.


Maintain a separate non-increasing stack, call it minStack. It does the following:
1. when there is new data pushed, push this new data to minStack if new data is <= the top of minStack or minStack is empty.
2. when there is data poped, pop minStack if the popped data equals with the top of minStack.

import java.util.Stack;

public class MinStack {

    private Stack<Integer> data;
    private Stack<Integer> min;
    
    /** initialize your data structure here. */
    public MinStack() {
        this.data = new Stack<Integer>();
        this.min = new Stack<Integer>();
        
    }
    
    public void push(int x) {
        this.data.push(x);
        
        //only push to the min stack when the value being pushed onto
        //the data stack is less than or equal to the current min value
        if(this.min.empty())
        {
            this.min.push(x);
        }
        else if(x <= this.min.peek())
        {
            this.min.push(x);
        }
    }
    
    public void pop() {
        int d = this.data.pop();

        //only pop from the min stack if the value that is popped from 
        //the data stack is equal to the current min value from min stack
        if(d == this.min.peek())
        {
            this.min.pop();
        }
    }
    
    public int top() {
        return this.data.peek();
    }
    
    public int getMin() {
        return this.min.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
 
原文地址:https://www.cnblogs.com/lz87/p/7500102.html