leetcode--Min Stack

来源:互联网 发布:php json数组 编辑:程序博客网 时间:2024/06/05 15:21

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.

解:

用stack存储当前值和当前最小值的gap,这样就可以根据stack值是否大于0来判断当前min值是当前值还是之前的min值

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)            if (x<min) min=x;        }    }    public void pop() {        if (stack.isEmpty()) return;        long pop=stack.pop();        if (pop<0)  min=min-pop;    }    public int top() {        long top=stack.peek();        if (top>0){            return (int)(top+min);        }else{           return (int)(min);        }    }    public int getMin() {        return (int)min;    }}
0 0
原创粉丝点击