Min Stack

</pre><p style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px">Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.</p><ul style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px"><li style="">push(x) -- Push element x onto stack.</li><li style="">pop() -- Removes the element on top of the stack.</li><li style="">top() -- Get the top element.</li><li style="">getMin() -- Retrieve the minimum element in the stack.</li></ul><p></p><p>思路:关键点在于获取最小值,一般的方法就是遍历整个容器,除非容器是有序的;但是栈本身无法实现在不影响他本身的情况下遍历,除非不断抛出最上方的元素,所以需要有一个额外的容器来存储每次栈中的元素,然后遍历他来找到最小值。</p><p></p><p><pre name="code" class="java">class MinStack {
    Stack<Integer> stack=new Stack<>();
    List<Integer> list=new ArrayList<>();
    public void push(int x) {
        stack.push(x);
        list.add(x);
    }

    public void pop() {
        stack.pop();
        list.remove(list.size()-1);
    }

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

    public int getMin() {
       int min=list.get(0); //注意将最小值设为第一位
		for(int i=0;i<list.size();i++){
		    if(min>list.get(i)) min=list.get(i);
		}
		return min;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值