LeetCode[stack]: Min Stack

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.

Discuss上的这个解法:https://oj.leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack 非常巧妙,算法的关键在于用一个stack保存了当前元素与最小元素的差。为了避免Integer.MAXVALUE-Integer.MINVALUE这个异常出现,采用Long类型来保存。Java代码如下:

public class MinStack {
    long min;
    Stack stack;

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

    public void push(int x) {
        if (stack.isEmpty()){
            stack.push(0L);
            min=x;
        }else{
            stack.push(x-min);//Could be negative if min value needs to change
            if (xpublic 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;
    }
}

这个算法的时间性能如下:

LeetCode[stack]: Min Stack_第1张图片

但是我在用C++实现相同的算法时却得到“Memory Limit Exceeded”,这是因为当用long类型时,其实无异于用两个stack。尽管如此,这个算法的思想还是值得学习的。

你可能感兴趣的:(LeetCode,LeetCode)