开始刷leetcode day8 : Min Stack

来源:互联网 发布:mac 打谱 编辑:程序博客网 时间:2024/06/05 06:06

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 {
    ArrayList<Integer> stack = new ArrayList<Integer>();
    ArrayList<Integer> minstack = new ArrayList<Integer>();
    public void push(int x) {
        if(minstack.size() == 0|| minstack.get(minstack.size()-1) >= x)
        {
            minstack.add(x);
        }
        stack.add(x);
    }


    public void pop() {
        int n = stack.get(stack.size()-1);
        if(minstack.size() >0 &&  n== minstack.get(minstack.size()-1))
        {    minstack.remove(minstack.size() - 1);}
        stack.remove(stack.size()-1);
    }


    public int top() {
        return stack.get(stack.size()-1);
        
    }


    public int getMin() {
        if( minstack.size() > 0)
        return minstack.get(minstack.size() -1);
        return 0;
    }
}


0 0
原创粉丝点击