본문 바로가기

Amazon/Leetcode

155. 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.


<SOLVE>


class MinStack {
    Stack <Integer> st1;
    Stack <Integer> st2;
    /** initialize your data structure here. */
    public MinStack() {
        st1 = new Stack<>();
        st2 = new Stack<>();
    }
   
    public void push(int x) {
        st1.push(x);
        if(st2.isEmpty()){
            st2.push(x);
        }
        else {
            st2.push(Math.min(st2.peek(), x));
        }
    }
   
    public void pop() {
        st1.pop();
        st2.pop();
    }
   
    public int top() {
        return st1.peek();
    }
   
    public int getMin() {
        return st2.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

'Amazon > Leetcode' 카테고리의 다른 글

238. Product of Array Except Self  (0) 2018.08.03
141. Linked List Cycle  (0) 2018.08.03
819. Most Common Word  (0) 2018.08.01
235. Lowest Common Ancestor of a Binary Search Tree  (0) 2018.07.31
206. Reverse Linked List  (0) 2018.07.29