1. 程式人生 > >LeetCode-Easy刷題(33) Min Stack

LeetCode-Easy刷題(33) 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.

Example:

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

建立一個棧物件,實現相應的方法.



public class MinStack {

    private int top = 0;
    private int[] stack;
    private int[] minStack;
    private int minTop=-1;
    /** initialize your data structure here. */
    public MinStack() {
        stack = new int[8];
        minStack = new int[8];
    }

    public void push(int x) {
        stack[top] = x;

        if(minTop <0 ||minStack[minTop] >=x){
            minTop++;
            minStack[minTop] = x;
        }

        if(minTop>=minStack.length-1){
            int[] newStack = new int[top*2];
            for (int i = 0; i < minStack.length; i++) {
                newStack[i] = minStack[i];
            }
            minStack = newStack;
        }

        top++;
        if(top >=stack.length){
            int[] newStack = new int[top*2];
            for (int i = 0; i < stack.length; i++) {
                newStack[i] = stack[i];
            }
            stack = newStack;
        }



    }

    public void pop() {
        int remove = stack[top-1];
        stack[top-1]=0;
        top--;
        if(remove ==minStack[minTop]){
            minStack[minTop] = 0;
            minTop--;
        }
    }

    public int top() {
        return stack[top-1];
    }

    public int getMin() {

        return minStack[minTop];
    }
}