Leetcode:155.最小栈(java)

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

  1. push(x) -- 将元素 x 推入栈中。
  2. pop() -- 删除栈顶的元素。
  3. top() -- 获取栈顶元素。
  4. getMin() -- 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

思路:

    使用一个辅助栈stackMin来保存栈中的最小元素。stackMin始终记录着stackData中的最小值,所以stackMin的栈顶元素始终是当前stackData中的最小值。

代码:

class MinStack {
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;
    /** 构造方法 */
    public MinStack() {
        stackData = new Stack<Integer>();
        stackMin = new Stack<Integer>();
    }
    
    /*将元素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();
    }
}

测评结果:

猜你喜欢

转载自blog.csdn.net/xiongmengyao/article/details/86698802