Min Stack

51 篇文章 0 订阅
5 篇文章 0 订阅

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.

Show Tags

Have you met this question in a real interview? 

思路 1 : 就是多设置一个 minStack来存储一下最小值, push  和 pop 时候判断一下。

思路2 : 这个具有更小的空间复杂度, 设置一个 min  作为标记, 在 stack 里面存储 和 min  的差值。

class MinStack {
    Stack<Integer> s = new Stack<Integer>();
    Stack<Integer> minStack = new Stack<Integer>();
    public void push(int x) {
        s.push(x);
        if(minStack.isEmpty() || x <= minStack.peek()){//-----
            minStack.push(x);
        }
    }

    public void pop() {
        int num = s.pop();
        if(num == minStack.peek()){
            minStack.pop();
        }
    }

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

    public int getMin() {
        return minStack.peek();
    }
}

public class MinStack {
    long min;
    Stack<Long> stack;//有减法,所以用long,将数据越界考虑在内

    public MinStack(){
        stack=new Stack<>();
    }

    public void push(int x) {
        if (stack.isEmpty()){
            stack.push(0L);
            min=x;
            return;
        }
        stack.push(x-min);//Could be negative if min value needs to change
        if (x<min) min=x;
    }

    public void pop() {
        if (stack.isEmpty()) return;

        long pop=stack.pop();

        if (pop<0)  min=min-pop;//If negative, increase the min value

    }

    public int top() {
        long top=stack.peek();
        if (top>0){
            return (int)(top+min);
        }else{
           return (int)(min);
        }
    }

    public int getMin() {
        return (int)min;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值