LeetCode -- Min Stack

Question:

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.

Analysis:

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

solution1: 利用Java内置的Stack类,并且设置一个格外的栈,当每次有元素进栈时都判断是否是额外栈的最小元素。这样当求最小元素时直接peek额外栈的栈顶元素即可。

solution2: 不适用Java内置的Stack类,每个栈节点维护一个最小值(是当前节点至栈底的最小值),其余操作与上面相同,只不过push,pop等基本操作要自己简单的实现一下。

 

Answer:

Solution1:

class MinStack {
    private Stack<Integer> stack = new Stack<Integer>();
    private Stack<Integer> minStack = new Stack<Integer>();
    public void push(int x) {
        if(minStack.isEmpty() || x <= minStack.peek()) //if x is the minimum value
            minStack.push(x);
        stack.push(x);
    }

    public void pop() {
        if(stack.peek().equals(minStack.peek())) //if the pop value is the minimum
            minStack.pop();
        stack.pop();    
    }

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

     public int getMin() {
         return minStack.peek();
     }
}

 

 

 

Solution2:

class MinStack {
   StackNode top = null;
    public void push(int x) {
        if(top == null) {
                top = new StackNode(x);
                top.min = x;
                top.next = null;
        }
        else {
                StackNode node = new StackNode(x);
                if(x < top.min)
                    node.min = x;
                else node.min = top.min;
                node.next = top;
                top = node;
        }
    }

    public void pop() {
        if(top != null)
                top = top.next;
    }

    public int top() {
        if(top != null)
                return top.val;
        else return 0;
    }

    public int getMin() {
        if(top != null)
                return top.min;
        else return 0;
    } 
}
class StackNode {
    int val;
    int min; //store the min utile this node 
    StackNode next;
    public StackNode(int x) {
        val = x;
    }
}

 

你可能感兴趣的:(LeetCode -- Min Stack)