leetcode中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.

该问题即要求设计一个栈,并能取回最小值(这个是最重要的)

##Java代码

class MinStack {
    static class Element{
        final int val;
        final int min;
        Element(final int val,final int min){
            this.val = val;
            this.min = min;
        }
    }

    final Stack<Element> stack = new Stack<>();

    public void push(int x) {
        final int min = (stack.empty() ? x : Math.min(stack.peek().min , x) );
        stack.push(new Element(x,min));
    }

    public void pop() {
        stack.pop();
    }

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

    public int getMin() {
        return stack.peek().min;
    }
}

##问题简单分析

利用java内置的stack类,注意把最小值和value又存在另外的一个Element类中