2015年3月23日星期一

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.

class MinStack {
   
    Stack<Integer> s = new Stack<Integer>();
    Stack<Integer> minS = new Stack<Integer>();
   
    public void push(int x) {
        s.push(x);
        if(minS.isEmpty() || x <= minS.peek()) {
           minS.push(x);
        }
    //    if(minS.isEmpty()) {
     //       minS.push(x);
      //  } else {
    //        minS.push(Math.min(x, minS.peek()));
    //    }
    }
    public void pop() {
        int i = s.peek();
        s.pop();
        if(i==minS.peek()) {
            minS.pop();
        }
    }
    public int top() {
        return s.peek();
    }
    public int getMin() {
        return minS.peek();
    }
}

=====

class MinStack {
 
    Stack<Integer> stk = new Stack<Integer>();
    Stack<Integer> minStk = new Stack<Integer>();
 
    public void push(int x) {
        stk.push(x);
        if (minStk.isEmpty()) {
            minStk.push(x);
        } else {
            int top = minStk.peek();
            minStk.push(Math.min(x, top));
        }
    }

    public void pop() {
        stk.pop();
        minStk.pop();
    }

    public int top() {
        return stk.peek();
    }

    public int getMin() {
        return minStk.peek();
    }
}

========

public class MinStack { long min; Stack<Long> stack; public MinStack(){ stack=new Stack<>(); } public void push(int x) { if (stack.isEmpty()){ stack.push(0L); min=x; }else{ stack.push(x-min);//Could be negative if min value needs to change if (x<min) min=x; } } public void pop() { if (stack.isEmpty()) return; long pop=stack.pop(); if (pop<0) min=min-pop;//If negative, increase the min value } public int top() { long top=stack.peek(); if (top>0){ return (int)(top+min); }else{ return (int)(min); } } public int getMin() { return (int)min; } }

没有评论:

发表评论