LeetCode155. 最小栈(java)

题目:

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。

示例:
LeetCode155. 最小栈(java)_第1张图片
代码:

  • 解法一
class MinStack {
    private Stack stackData;
    private Stack stackMin;
    /** 构造方法 */
    public MinStack() {
        stackData = new Stack();
        stackMin = new Stack();
    }
    
    /*将元素x推入栈中*/
    public void push(int x) {
        if(stackMin.empty()) {
            stackMin.push(x);
        } else if(x <= getMin()) {
            stackMin.push(x);
        } else {
            int newMin = getMin();
            stackMin.push(newMin);
        }
        stackData.push(x);
    }
    
    /*删除栈顶元素*/
    public void pop() {
        if(stackData.empty()) {
            throw new RuntimeException("your stack is empty!");
        }
        stackMin.pop();
        stackData.pop();
    }
    
    /*获取栈顶元素*/
    public int top() {
        if(stackData.empty()) {
            throw new RuntimeException("your stack is empty!");
        }
        return stackData.peek();
    }
    
    /*检索栈中的最小元素*/
    public int getMin() {
        if(stackMin.empty()) {
            throw new RuntimeException("your stack is empty!");
        }
        return stackMin.peek();
    }
}

  • 解法二
class MinStack {
    // 支持push,pop,top的栈
    private Stack mainStack;
    // 支持在常数时间内检索到最小元素的单调栈
    private Stack minStack;

    /** initialize your data structure here. */
    public MinStack() {
        this.mainStack = new Stack<>();
        this.minStack = new Stack<>();
    }

    public void push(int x) {
        mainStack.push(x);
        // 实际上每次push只需要记录更小的值
        if(minStack.isEmpty() || minStack.peek() >= x)
            minStack.push(x);
    }
	//弹栈
    public void pop() {
        int tmp = mainStack.pop();
        if(tmp == minStack.peek())
            minStack.pop();
    }
	//获取栈顶元素
    public int top() {
        return mainStack.peek();
    }
	//获取最小元素
    public int getMin() {
        return minStack.peek();
    }
}

  • 别人的代码
class MinStack {
    private Deque mainStack; // 主栈,存储所有数据
    
    private Deque minStack; // 将数据压入主栈时,存储最小值

    /** initialize your data structure here. */
    public MinStack() {
        mainStack = new ArrayDeque<>();
        minStack = new ArrayDeque<>();
    }
    
    public void push(int x) {
        mainStack.push(x);
        
        Integer min = minStack.peek();
        if (min == null || x <= min) {
            minStack.push(x);
        }
    }
    
    public int pop() {
        int cur = mainStack.pop();
        if (cur == minStack.peek()) {
            minStack.pop();
        }
        return cur;
        
    }
    
    public int top() {
        return mainStack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

你可能感兴趣的:(LeetCode刷题)