1.3 Min Stack 155

Description

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.

Hint

stack : last in first out

Method

two stack

Time & Space

pop : o (1)

push : o (1)

min: o(1)

peek : o (1)

Code

<

public class MinStack {

Stack<Integer> min;

Stack<Integer> nums;

/** initialize your data structure here. */

public MinStack() {

min = new Stack<Integer>();

nums = new Stack<Integer>();

}

public void push(int x) {

nums.push(x);

if (min.isEmpty() || x <= min.peek()){

min.push(x);

}

}

public void pop() {

if (min.peek().equals(nums.peek())){

// System.out.println("POP MIN");

min.pop();

}

//System.out.println("****" + min.peek());

nums.pop();

}

public int top() {

return nums.peek();

}

public int getMin() {

return min.peek();

}

}

>

results matching ""

    No results matching ""