[LintCode] 带最小值操作的栈 Min Stack

来源:互联网 发布:java业余培训 编辑:程序博客网 时间:2024/05/29 13:19

实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。
你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。

样例
如下操作:push(1),pop(),push(2),push(3),min(), push(1),min() 返回 1,2,1

Implement a stack with min() function, which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.

Notice
min operation will never be called if there is no number in the stack.

Example
push(1)
pop() // return 1
push(2)
push(3)
min() // return 2
push(1)
min() // return 1

参考:http://blog.csdn.net/anchor89/article/details/6055412
http://blog.csdn.net/anchor89/article/details/6055412

public class MinStack {    Stack<Integer> stack;    int min;    public MinStack() {        stack = new Stack<Integer>();        min = 0;    }    public void push(int number) {        if(stack.size() == 0) {            stack.push(number);            min = number;        } else{            if(number >= min) {                stack.push(number);            }else {                stack.push(2*number - min);                min = number;            }        }    }    public int pop() {        if(!stack.isEmpty()) {            int temp = stack.pop();            if(temp < min) {                int num = min;                min = 2*min - temp;                temp = num;            }            return temp;        }else {            return min;        }    }    public int min() {        return min;    }}
0 0