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.
class MinStack {// 栈 my

    List<Integer> list ;
    int num;
    int min;    

    /** initialize your data structure here. */
    public MinStack() {
        list= new ArrayList<Integer>();
        num =0;
        min=Integer.MAX_VALUE;
    }
    
    public void push(int x) {
        list.add(x);
        num++;
        if(min>x){
            min=x;
        }
    }
    
    public void pop() {
        if (0<num){
            if(min == list.get(num-1)){
                min=Integer.MAX_VALUE;
                for (int i = 0; i < num-1; i++) {
                    if(min>list.get(i)){
                        min=list.get(i);
                    }
                }
            }
            list.remove(num-1);
            num--;
        }
    }
    
    public int top() {
        return num>0?list.get(num-1):0;
    }
    
    public int getMin() {
        return min;
    }
}  

 

时间复杂度为O(1)的解法

class MinStack {

    Stack<Integer> minStack ;
    Stack<Integer> stack;
    int min=Integer.MAX_VALUE; 

    /** initialize your data structure here. */
    public MinStack() {
        stack=new Stack<Integer>();
        minStack = new Stack<Integer>();
        min=Integer.MAX_VALUE;
    }
    
    public void push(int x) {
        stack.push(x);
        if(min>x){
            min=x;
        }
        minStack.push(min);
    }
    
    public void pop() {
        if(!stack.isEmpty()){
            minStack.pop();
            stack.pop();            
        }
        if(stack.isEmpty()){
            min = Integer.MAX_VALUE;
        }
        else{
            min = minStack.peek();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min;
    }
}

  

 

posted @ 2019-02-25 09:50  月半榨菜  阅读(87)  评论(0编辑  收藏  举报