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

98 篇文章 0 订阅
4 篇文章 0 订阅

实现一个带有取最小值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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值