Leetcode 155: Min Stack

Description:

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.

Solution:
1. My solution:

class MinStack {
    Stack<Integer> s;
    Stack<Integer> temp;
    int ans;

    /** initialize your data structure here. */
    public MinStack() {
        s = new Stack<>(); 
        temp = new Stack<>();
    }
    
    public void push(int x) {
        if(s.isEmpty()){
            s.push(x);
            temp.push(x);
        }
        else{
            s.push(x);
            int min = temp.peek();
            if(min > x)
                temp.push(x);
            else
                temp.push(min);
        }
    }
    
    public int pop() {
        if(s.isEmpty())
            return -1;
        else{
            int pop = s.peek();
            s.pop();
            temp.pop();
            return pop;
        }          
    }
    
    public int top() {
        int v = s.peek();
        return v;
    }
    
    public int getMin() {
        ans = temp.peek();
        return ans;
    }
}

/**
 * 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();
 */

2. Best Solution:
   这种方法只用了一个栈,通过进栈当前值和min的差值,来同时记录min和当前进栈值。
class MinStack {
    /*
    using a stack to save the gap between current value and the min value
    if the gap is negative, it is current min value
    */
    public Stack<Long> s;
    public long min;
    /** initialize your data structure here. */
    public MinStack() {
        s=new Stack<Long>();
        min=0;
    }
    
    public void push(int x) {
        if(s.size()==0){
           // s.push(0L);
            min=x;
        }
            
        s.push(x-min);
        if(x-min<0)
            min=x;
    }
    
    public void pop() {
        if(s.isEmpty())
            return;
        long x=s.pop();
        if(x<0)
            min-=x;
    }
    
    public int top() {
        long top=s.peek();
        if (top>0){
            return (int)(top+min);
        }else{
           return (int)(min);
        }
    }
    
    public int getMin() {
        return (int)min;
    }
}

/**
 * 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();
 */

猜你喜欢

转载自blog.csdn.net/weixin_41876155/article/details/80195233